]> git.ipfire.org Git - thirdparty/git.git/blame - sequencer.c
t7502: clean up style
[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"
cbd53a21 5#include "object-store.h"
043a4492
RR
6#include "object.h"
7#include "commit.h"
0505d604 8#include "sequencer.h"
043a4492
RR
9#include "tag.h"
10#include "run-command.h"
d807c4a0 11#include "exec-cmd.h"
043a4492
RR
12#include "utf8.h"
13#include "cache-tree.h"
14#include "diff.h"
15#include "revision.h"
16#include "rerere.h"
17#include "merge-recursive.h"
18#include "refs.h"
b27cfb0d 19#include "argv-array.h"
a1c75762 20#include "quote.h"
967dfd4d 21#include "trailer.h"
56dc3ab0 22#include "log-tree.h"
311af526 23#include "wt-status.h"
c44a4c65 24#include "hashmap.h"
a87a6f3c
PW
25#include "notes-utils.h"
26#include "sigchain.h"
9055e401
JS
27#include "unpack-trees.h"
28#include "worktree.h"
1644c73c
JS
29#include "oidmap.h"
30#include "oidset.h"
8315bd20 31#include "commit-slab.h"
65b5f948 32#include "alias.h"
64043556 33#include "commit-reach.h"
b97e1873 34#include "rebase-interactive.h"
043a4492
RR
35
36#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
26ae337b 37
5fe81438 38static const char sign_off_header[] = "Signed-off-by: ";
cd650a4e 39static const char cherry_picked_prefix[] = "(cherry picked from commit ";
5ed75e2a 40
66618a50
PW
41GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
42
8a2a0f53
JS
43GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
44
45static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
46static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
47static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
1e41229d 48static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
f932729c 49
84583957
JS
50static GIT_PATH_FUNC(rebase_path, "rebase-merge")
51/*
52 * The file containing rebase commands, comments, and empty lines.
53 * This file is created by "git rebase -i" then edited by the user. As
54 * the lines are processed, they are removed from the front of this
55 * file and written to the tail of 'done'.
56 */
44b776c3 57GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
b97e1873
AG
58static GIT_PATH_FUNC(rebase_path_todo_backup,
59 "rebase-merge/git-rebase-todo.backup")
60
1df6df0c
JS
61/*
62 * The rebase command lines that have already been processed. A line
63 * is moved here when it is first handled, before any associated user
64 * actions.
65 */
66static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
ef80069a
JS
67/*
68 * The file to keep track of how many commands were already processed (e.g.
69 * for the prompt).
70 */
9ad36356 71static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
ef80069a
JS
72/*
73 * The file to keep track of how many commands are to be processed in total
74 * (e.g. for the prompt).
75 */
9ad36356 76static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
6e98de72
JS
77/*
78 * The commit message that is planned to be used for any changes that
79 * need to be committed following a user interaction.
80 */
81static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
82/*
83 * The file into which is accumulated the suggested commit message for
84 * squash/fixup commands. When the first of a series of squash/fixups
85 * is seen, the file is created and the commit message from the
86 * previous commit and from the first squash/fixup commit are written
87 * to it. The commit message for each subsequent squash/fixup commit
88 * is appended to the file as it is processed.
6e98de72
JS
89 */
90static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
91/*
92 * If the current series of squash/fixups has not yet included a squash
93 * command, then this file exists and holds the commit message of the
94 * original "pick" commit. (If the series ends without a "squash"
95 * command, then this can be used as the commit message of the combined
96 * commit without opening the editor.)
97 */
98static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
e12a7ef5
JS
99/*
100 * This file contains the list fixup/squash commands that have been
101 * accumulated into message-fixup or message-squash so far.
102 */
103static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
b5a67045
JS
104/*
105 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
106 * GIT_AUTHOR_DATE that will be used for the commit that is currently
107 * being rebased.
108 */
109static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
56dc3ab0
JS
110/*
111 * When an "edit" rebase command is being processed, the SHA1 of the
112 * commit to be edited is recorded in this file. When "git rebase
113 * --continue" is executed, if there are any staged changes then they
114 * will be amended to the HEAD commit, but only provided the HEAD
115 * commit is still the commit to be edited. When any other rebase
116 * command is processed, this file is deleted.
117 */
118static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
119/*
120 * When we stop at a given patch via the "edit" command, this file contains
121 * the abbreviated commit name of the corresponding patch.
122 */
123static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
25cb8df9
JS
124/*
125 * For the post-rewrite hook, we make a list of rewritten commits and
126 * their new sha1s. The rewritten-pending list keeps the sha1s of
127 * commits that have been processed, but not committed yet,
128 * e.g. because they are waiting for a 'squash' command.
129 */
130static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
131static GIT_PATH_FUNC(rebase_path_rewritten_pending,
132 "rebase-merge/rewritten-pending")
9055e401 133
d87d48b2
JS
134/*
135 * The path of the file containig the OID of the "squash onto" commit, i.e.
136 * the dummy commit used for `reset [new root]`.
137 */
138static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
139
9055e401
JS
140/*
141 * The path of the file listing refs that need to be deleted after the rebase
142 * finishes. This is used by the `label` command to record the need for cleanup.
143 */
144static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
145
a1c75762
JS
146/*
147 * The following files are written by git-rebase just after parsing the
65850686 148 * command-line.
a1c75762
JS
149 */
150static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
556907f1
JS
151static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
152static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
899b49c4 153static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
a852ec7f 154static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
4b83ce9f
JS
155static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
156static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
796c7972 157static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
ca6c6b45
JS
158static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
159static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
9b6d7a62 160static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
d421afa0 161static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
b5a67045 162
28d6daed
PW
163static int git_sequencer_config(const char *k, const char *v, void *cb)
164{
165 struct replay_opts *opts = cb;
166 int status;
167
168 if (!strcmp(k, "commit.cleanup")) {
169 const char *s;
170
171 status = git_config_string(&s, k, v);
172 if (status)
173 return status;
174
d74f3e58 175 if (!strcmp(s, "verbatim")) {
28d6daed 176 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
d74f3e58
PW
177 opts->explicit_cleanup = 1;
178 } else if (!strcmp(s, "whitespace")) {
28d6daed 179 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
d74f3e58
PW
180 opts->explicit_cleanup = 1;
181 } else if (!strcmp(s, "strip")) {
28d6daed 182 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
d74f3e58
PW
183 opts->explicit_cleanup = 1;
184 } else if (!strcmp(s, "scissors")) {
28d6daed 185 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
d74f3e58
PW
186 opts->explicit_cleanup = 1;
187 } else {
28d6daed
PW
188 warning(_("invalid commit message cleanup mode '%s'"),
189 s);
d74f3e58 190 }
28d6daed 191
f40f3c16 192 free((char *)s);
28d6daed
PW
193 return status;
194 }
195
196 if (!strcmp(k, "commit.gpgsign")) {
ed1e5282 197 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
28d6daed
PW
198 return 0;
199 }
200
201 status = git_gpg_config(k, v, NULL);
202 if (status)
203 return status;
204
205 return git_diff_basic_config(k, v, NULL);
206}
207
208void sequencer_init_config(struct replay_opts *opts)
209{
210 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
211 git_config(git_sequencer_config, opts);
212}
213
b5a67045
JS
214static inline int is_rebase_i(const struct replay_opts *opts)
215{
84583957 216 return opts->action == REPLAY_INTERACTIVE_REBASE;
b5a67045
JS
217}
218
285abf56
JS
219static const char *get_dir(const struct replay_opts *opts)
220{
84583957
JS
221 if (is_rebase_i(opts))
222 return rebase_path();
285abf56
JS
223 return git_path_seq_dir();
224}
225
c0246501
JS
226static const char *get_todo_path(const struct replay_opts *opts)
227{
84583957
JS
228 if (is_rebase_i(opts))
229 return rebase_path_todo();
c0246501
JS
230 return git_path_todo_file();
231}
232
bab4d109
BC
233/*
234 * Returns 0 for non-conforming footer
235 * Returns 1 for conforming footer
236 * Returns 2 when sob exists within conforming footer
237 * Returns 3 when sob exists within conforming footer as last entry
238 */
239static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
66e83d9b 240 size_t ignore_footer)
b971e04f 241{
00a21f5c 242 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
967dfd4d 243 struct trailer_info info;
a3b636e2 244 size_t i;
967dfd4d 245 int found_sob = 0, found_sob_last = 0;
b971e04f 246
ffce7f59
JK
247 opts.no_divider = 1;
248
00a21f5c 249 trailer_info_get(&info, sb->buf, &opts);
b971e04f 250
967dfd4d 251 if (info.trailer_start == info.trailer_end)
b971e04f
BC
252 return 0;
253
967dfd4d
JT
254 for (i = 0; i < info.trailer_nr; i++)
255 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
256 found_sob = 1;
257 if (i == info.trailer_nr - 1)
258 found_sob_last = 1;
259 }
b971e04f 260
967dfd4d 261 trailer_info_release(&info);
bab4d109 262
967dfd4d 263 if (found_sob_last)
bab4d109
BC
264 return 3;
265 if (found_sob)
266 return 2;
b971e04f
BC
267 return 1;
268}
5ed75e2a 269
a1c75762
JS
270static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
271{
272 static struct strbuf buf = STRBUF_INIT;
273
274 strbuf_reset(&buf);
275 if (opts->gpg_sign)
276 sq_quotef(&buf, "-S%s", opts->gpg_sign);
277 return buf.buf;
278}
279
2863584f 280int sequencer_remove_state(struct replay_opts *opts)
26ae337b 281{
9055e401 282 struct strbuf buf = STRBUF_INIT;
03a4e260
JS
283 int i;
284
9055e401
JS
285 if (is_rebase_i(opts) &&
286 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
287 char *p = buf.buf;
288 while (*p) {
289 char *eol = strchr(p, '\n');
290 if (eol)
291 *eol = '\0';
292 if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0)
293 warning(_("could not delete '%s'"), p);
294 if (!eol)
295 break;
296 p = eol + 1;
297 }
298 }
299
03a4e260
JS
300 free(opts->gpg_sign);
301 free(opts->strategy);
302 for (i = 0; i < opts->xopts_nr; i++)
303 free(opts->xopts[i]);
304 free(opts->xopts);
e12a7ef5 305 strbuf_release(&opts->current_fixups);
26ae337b 306
9055e401
JS
307 strbuf_reset(&buf);
308 strbuf_addstr(&buf, get_dir(opts));
309 remove_dir_recursively(&buf, 0);
310 strbuf_release(&buf);
2863584f
JS
311
312 return 0;
26ae337b 313}
043a4492
RR
314
315static const char *action_name(const struct replay_opts *opts)
316{
84583957
JS
317 switch (opts->action) {
318 case REPLAY_REVERT:
319 return N_("revert");
320 case REPLAY_PICK:
321 return N_("cherry-pick");
322 case REPLAY_INTERACTIVE_REBASE:
323 return N_("rebase -i");
324 }
1a07e59c 325 die(_("unknown action: %d"), opts->action);
043a4492
RR
326}
327
043a4492
RR
328struct commit_message {
329 char *parent_label;
7b35eaf8
JK
330 char *label;
331 char *subject;
043a4492
RR
332 const char *message;
333};
334
39755964
JS
335static const char *short_commit_name(struct commit *commit)
336{
aab9583f 337 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
39755964
JS
338}
339
043a4492
RR
340static int get_message(struct commit *commit, struct commit_message *out)
341{
043a4492 342 const char *abbrev, *subject;
7b35eaf8 343 int subject_len;
043a4492 344
7b35eaf8 345 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
39755964 346 abbrev = short_commit_name(commit);
043a4492
RR
347
348 subject_len = find_commit_subject(out->message, &subject);
349
7b35eaf8
JK
350 out->subject = xmemdupz(subject, subject_len);
351 out->label = xstrfmt("%s... %s", abbrev, out->subject);
352 out->parent_label = xstrfmt("parent of %s", out->label);
353
043a4492
RR
354 return 0;
355}
356
d74a4e57 357static void free_message(struct commit *commit, struct commit_message *msg)
043a4492
RR
358{
359 free(msg->parent_label);
7b35eaf8
JK
360 free(msg->label);
361 free(msg->subject);
b66103c3 362 unuse_commit_buffer(commit, msg->message);
043a4492
RR
363}
364
005af339
NTND
365static void print_advice(struct repository *r, int show_hint,
366 struct replay_opts *opts)
043a4492
RR
367{
368 char *msg = getenv("GIT_CHERRY_PICK_HELP");
369
370 if (msg) {
371 fprintf(stderr, "%s\n", msg);
372 /*
41ccfdd9 373 * A conflict has occurred but the porcelain
043a4492
RR
374 * (typically rebase --interactive) wants to take care
375 * of the commit itself so remove CHERRY_PICK_HEAD
376 */
005af339 377 unlink(git_path_cherry_pick_head(r));
043a4492
RR
378 return;
379 }
380
ed727b19
PH
381 if (show_hint) {
382 if (opts->no_commit)
383 advise(_("after resolving the conflicts, mark the corrected paths\n"
384 "with 'git add <paths>' or 'git rm <paths>'"));
385 else
386 advise(_("after resolving the conflicts, mark the corrected paths\n"
387 "with 'git add <paths>' or 'git rm <paths>'\n"
388 "and commit the result with 'git commit'"));
389 }
043a4492
RR
390}
391
44b776c3
AG
392int write_message(const void *buf, size_t len, const char *filename,
393 int append_eol)
043a4492 394{
14bca6c6 395 struct lock_file msg_file = LOCK_INIT;
043a4492 396
4ef3d8f0
JS
397 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
398 if (msg_fd < 0)
93b3df6f 399 return error_errno(_("could not lock '%s'"), filename);
75871495 400 if (write_in_full(msg_fd, buf, len) < 0) {
bf5c0571 401 error_errno(_("could not write to '%s'"), filename);
4f66c837 402 rollback_lock_file(&msg_file);
bf5c0571 403 return -1;
4f66c837 404 }
f56fffef 405 if (append_eol && write(msg_fd, "\n", 1) < 0) {
bf5c0571 406 error_errno(_("could not write eol to '%s'"), filename);
f56fffef 407 rollback_lock_file(&msg_file);
bf5c0571 408 return -1;
f56fffef 409 }
350292a1
410 if (commit_lock_file(&msg_file) < 0)
411 return error(_("failed to finalize '%s'"), filename);
4ef3d8f0
JS
412
413 return 0;
043a4492
RR
414}
415
1dfc84e9
JS
416/*
417 * Reads a file that was presumably written by a shell script, i.e. with an
418 * end-of-line marker that needs to be stripped.
419 *
420 * Note that only the last end-of-line marker is stripped, consistent with the
421 * behavior of "$(cat path)" in a shell script.
422 *
423 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
424 */
425static int read_oneliner(struct strbuf *buf,
426 const char *path, int skip_if_empty)
427{
428 int orig_len = buf->len;
429
430 if (!file_exists(path))
431 return 0;
432
433 if (strbuf_read_file(buf, path, 0) < 0) {
434 warning_errno(_("could not read '%s'"), path);
435 return 0;
436 }
437
438 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
439 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
440 --buf->len;
441 buf->buf[buf->len] = '\0';
442 }
443
444 if (skip_if_empty && buf->len == orig_len)
445 return 0;
446
447 return 1;
448}
449
005af339 450static struct tree *empty_tree(struct repository *r)
043a4492 451{
005af339 452 return lookup_tree(r, the_hash_algo->empty_tree);
043a4492
RR
453}
454
e1ff0a32 455static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
043a4492 456{
e1ff0a32 457 if (repo_read_index_unmerged(repo))
c28cbc5e 458 return error_resolve_conflict(_(action_name(opts)));
043a4492 459
93b3df6f 460 error(_("your local changes would be overwritten by %s."),
c28cbc5e 461 _(action_name(opts)));
043a4492
RR
462
463 if (advice_commit_before_merge)
93b3df6f 464 advise(_("commit your changes or stash them to proceed."));
043a4492
RR
465 return -1;
466}
467
1e41229d
SB
468static void update_abort_safety_file(void)
469{
470 struct object_id head;
471
472 /* Do nothing on a single-pick */
473 if (!file_exists(git_path_seq_dir()))
474 return;
475
476 if (!get_oid("HEAD", &head))
477 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
478 else
479 write_file(git_path_abort_safety_file(), "%s", "");
480}
481
f11c9580
NTND
482static int fast_forward_to(struct repository *r,
483 const struct object_id *to,
484 const struct object_id *from,
485 int unborn,
486 struct replay_opts *opts)
043a4492 487{
d668d16c 488 struct ref_transaction *transaction;
eb4be1cb 489 struct strbuf sb = STRBUF_INIT;
d668d16c 490 struct strbuf err = STRBUF_INIT;
043a4492 491
e1ff0a32 492 repo_read_index(r);
f11c9580 493 if (checkout_fast_forward(r, from, to, 1))
0e408fc3 494 return -1; /* the callee should have complained already */
651ab9f5 495
c28cbc5e 496 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
d668d16c
RS
497
498 transaction = ref_transaction_begin(&err);
499 if (!transaction ||
500 ref_transaction_update(transaction, "HEAD",
d87d48b2
JS
501 to, unborn && !is_rebase_i(opts) ?
502 &null_oid : from,
1d147bdf 503 0, sb.buf, &err) ||
db7516ab 504 ref_transaction_commit(transaction, &err)) {
d668d16c
RS
505 ref_transaction_free(transaction);
506 error("%s", err.buf);
507 strbuf_release(&sb);
508 strbuf_release(&err);
509 return -1;
510 }
651ab9f5 511
eb4be1cb 512 strbuf_release(&sb);
d668d16c
RS
513 strbuf_release(&err);
514 ref_transaction_free(transaction);
1e41229d 515 update_abort_safety_file();
d668d16c 516 return 0;
043a4492
RR
517}
518
f11c9580
NTND
519void append_conflicts_hint(struct index_state *istate,
520 struct strbuf *msgbuf)
75c961b7
JH
521{
522 int i;
523
261f315b
JH
524 strbuf_addch(msgbuf, '\n');
525 strbuf_commented_addf(msgbuf, "Conflicts:\n");
f11c9580
NTND
526 for (i = 0; i < istate->cache_nr;) {
527 const struct cache_entry *ce = istate->cache[i++];
75c961b7 528 if (ce_stage(ce)) {
261f315b 529 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
f11c9580
NTND
530 while (i < istate->cache_nr &&
531 !strcmp(ce->name, istate->cache[i]->name))
75c961b7
JH
532 i++;
533 }
534 }
535}
536
f11c9580
NTND
537static int do_recursive_merge(struct repository *r,
538 struct commit *base, struct commit *next,
043a4492 539 const char *base_label, const char *next_label,
48be4c62 540 struct object_id *head, struct strbuf *msgbuf,
043a4492
RR
541 struct replay_opts *opts)
542{
543 struct merge_options o;
544 struct tree *result, *next_tree, *base_tree, *head_tree;
03b86647 545 int clean;
03a4e260 546 char **xopt;
14bca6c6 547 struct lock_file index_lock = LOCK_INIT;
043a4492 548
3a95f31d 549 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
bd588867 550 return -1;
043a4492 551
e1ff0a32 552 repo_read_index(r);
043a4492 553
0d6caa2d 554 init_merge_options(&o, r);
043a4492
RR
555 o.ancestor = base ? base_label : "(empty tree)";
556 o.branch1 = "HEAD";
557 o.branch2 = next ? next_label : "(empty tree)";
62fdb652
JS
558 if (is_rebase_i(opts))
559 o.buffer_output = 2;
9268cf4a 560 o.show_rename_progress = 1;
043a4492
RR
561
562 head_tree = parse_tree_indirect(head);
005af339
NTND
563 next_tree = next ? get_commit_tree(next) : empty_tree(r);
564 base_tree = base ? get_commit_tree(base) : empty_tree(r);
043a4492
RR
565
566 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
567 parse_merge_opt(&o, *xopt);
568
569 clean = merge_trees(&o,
570 head_tree,
571 next_tree, base_tree, &result);
62fdb652
JS
572 if (is_rebase_i(opts) && clean <= 0)
573 fputs(o.obuf.buf, stdout);
548009c0 574 strbuf_release(&o.obuf);
b520abf1 575 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
64816524
576 if (clean < 0) {
577 rollback_lock_file(&index_lock);
f241ff0d 578 return clean;
64816524 579 }
043a4492 580
f11c9580 581 if (write_locked_index(r->index, &index_lock,
61000814 582 COMMIT_LOCK | SKIP_IF_UNCHANGED))
66f5f6dc
ÆAB
583 /*
584 * TRANSLATORS: %s will be "revert", "cherry-pick" or
84583957
JS
585 * "rebase -i".
586 */
c527b55e 587 return error(_("%s: Unable to write new index file"),
c28cbc5e 588 _(action_name(opts)));
043a4492 589
75c961b7 590 if (!clean)
f11c9580 591 append_conflicts_hint(r->index, msgbuf);
043a4492
RR
592
593 return !clean;
594}
595
f11c9580 596static struct object_id *get_cache_tree_oid(struct index_state *istate)
ba97aea1 597{
f11c9580
NTND
598 if (!istate->cache_tree)
599 istate->cache_tree = cache_tree();
ba97aea1 600
f11c9580
NTND
601 if (!cache_tree_fully_valid(istate->cache_tree))
602 if (cache_tree_update(istate, 0)) {
ba97aea1
JS
603 error(_("unable to update cache tree"));
604 return NULL;
605 }
606
f11c9580 607 return &istate->cache_tree->oid;
ba97aea1
JS
608}
609
005af339 610static int is_index_unchanged(struct repository *r)
b27cfb0d 611{
ba97aea1 612 struct object_id head_oid, *cache_tree_oid;
b27cfb0d 613 struct commit *head_commit;
005af339 614 struct index_state *istate = r->index;
b27cfb0d 615
49e61479 616 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
aee42e1f 617 return error(_("could not resolve HEAD commit"));
b27cfb0d 618
005af339 619 head_commit = lookup_commit(r, &head_oid);
4b580061
NH
620
621 /*
622 * If head_commit is NULL, check_commit, called from
623 * lookup_commit, would have indicated that head_commit is not
624 * a commit object already. parse_commit() will return failure
625 * without further complaints in such a case. Otherwise, if
626 * the commit is invalid, parse_commit() will complain. So
627 * there is nothing for us to say here. Just return failure.
628 */
629 if (parse_commit(head_commit))
630 return -1;
b27cfb0d 631
f11c9580 632 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
ba97aea1 633 return -1;
b27cfb0d 634
4a7e27e9 635 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
b27cfb0d
NH
636}
637
0473f28a
JS
638static int write_author_script(const char *message)
639{
640 struct strbuf buf = STRBUF_INIT;
641 const char *eol;
642 int res;
643
644 for (;;)
645 if (!*message || starts_with(message, "\n")) {
646missing_author:
647 /* Missing 'author' line? */
648 unlink(rebase_path_author_script());
649 return 0;
650 } else if (skip_prefix(message, "author ", &message))
651 break;
652 else if ((eol = strchr(message, '\n')))
653 message = eol + 1;
654 else
655 goto missing_author;
656
657 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
658 while (*message && *message != '\n' && *message != '\r')
659 if (skip_prefix(message, " <", &message))
660 break;
661 else if (*message != '\'')
662 strbuf_addch(&buf, *(message++));
663 else
4aa5ff94 664 strbuf_addf(&buf, "'\\%c'", *(message++));
0473f28a
JS
665 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
666 while (*message && *message != '\n' && *message != '\r')
667 if (skip_prefix(message, "> ", &message))
668 break;
669 else if (*message != '\'')
670 strbuf_addch(&buf, *(message++));
671 else
4aa5ff94 672 strbuf_addf(&buf, "'\\%c'", *(message++));
0473f28a
JS
673 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
674 while (*message && *message != '\n' && *message != '\r')
675 if (*message != '\'')
676 strbuf_addch(&buf, *(message++));
677 else
4aa5ff94 678 strbuf_addf(&buf, "'\\%c'", *(message++));
0f16c09a 679 strbuf_addch(&buf, '\'');
0473f28a
JS
680 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
681 strbuf_release(&buf);
682 return res;
683}
684
bcd33ec2
PW
685/**
686 * Take a series of KEY='VALUE' lines where VALUE part is
687 * sq-quoted, and append <KEY, VALUE> at the end of the string list
688 */
689static int parse_key_value_squoted(char *buf, struct string_list *list)
690{
691 while (*buf) {
692 struct string_list_item *item;
693 char *np;
694 char *cp = strchr(buf, '=');
695 if (!cp) {
696 np = strchrnul(buf, '\n');
697 return error(_("no key present in '%.*s'"),
698 (int) (np - buf), buf);
699 }
700 np = strchrnul(cp, '\n');
701 *cp++ = '\0';
702 item = string_list_append(list, buf);
703
704 buf = np + (*np == '\n');
705 *np = '\0';
706 cp = sq_dequote(cp);
707 if (!cp)
708 return error(_("unable to dequote value of '%s'"),
709 item->string);
710 item->util = xstrdup(cp);
711 }
712 return 0;
713}
4aa5ff94 714
bcd33ec2
PW
715/**
716 * Reads and parses the state directory's "author-script" file, and sets name,
717 * email and date accordingly.
718 * Returns 0 on success, -1 if the file could not be parsed.
719 *
720 * The author script is of the format:
721 *
722 * GIT_AUTHOR_NAME='$author_name'
723 * GIT_AUTHOR_EMAIL='$author_email'
724 * GIT_AUTHOR_DATE='$author_date'
725 *
726 * where $author_name, $author_email and $author_date are quoted. We are strict
727 * with our parsing, as the file was meant to be eval'd in the old
728 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
729 * from what this function expects, it is better to bail out than to do
730 * something that the user does not expect.
4aa5ff94 731 */
bcd33ec2
PW
732int read_author_script(const char *path, char **name, char **email, char **date,
733 int allow_missing)
4aa5ff94 734{
bcd33ec2
PW
735 struct strbuf buf = STRBUF_INIT;
736 struct string_list kv = STRING_LIST_INIT_DUP;
737 int retval = -1; /* assume failure */
738 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
4aa5ff94 739
bcd33ec2
PW
740 if (strbuf_read_file(&buf, path, 256) <= 0) {
741 strbuf_release(&buf);
742 if (errno == ENOENT && allow_missing)
743 return 0;
744 else
745 return error_errno(_("could not open '%s' for reading"),
746 path);
747 }
748
749 if (parse_key_value_squoted(buf.buf, &kv))
750 goto finish;
751
752 for (i = 0; i < kv.nr; i++) {
753 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
754 if (name_i != -2)
755 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
756 else
757 name_i = i;
758 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
759 if (email_i != -2)
760 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
761 else
762 email_i = i;
763 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
764 if (date_i != -2)
765 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
766 else
767 date_i = i;
768 } else {
769 err = error(_("unknown variable '%s'"),
770 kv.items[i].string);
771 }
772 }
773 if (name_i == -2)
774 error(_("missing 'GIT_AUTHOR_NAME'"));
775 if (email_i == -2)
776 error(_("missing 'GIT_AUTHOR_EMAIL'"));
777 if (date_i == -2)
778 error(_("missing 'GIT_AUTHOR_DATE'"));
779 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
780 goto finish;
781 *name = kv.items[name_i].util;
782 *email = kv.items[email_i].util;
783 *date = kv.items[date_i].util;
784 retval = 0;
785finish:
786 string_list_clear(&kv, !!retval);
787 strbuf_release(&buf);
788 return retval;
4aa5ff94
PW
789}
790
b5a67045 791/*
4d010a75
PW
792 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
793 * file with shell quoting into struct argv_array. Returns -1 on
794 * error, 0 otherwise.
b5a67045 795 */
a2a20b0d 796static int read_env_script(struct argv_array *env)
b5a67045 797{
4d010a75 798 char *name, *email, *date;
b5a67045 799
4d010a75
PW
800 if (read_author_script(rebase_path_author_script(),
801 &name, &email, &date, 0))
a2a20b0d 802 return -1;
b5a67045 803
4d010a75
PW
804 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
805 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
806 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
807 free(name);
808 free(email);
809 free(date);
b5a67045 810
a2a20b0d 811 return 0;
b5a67045
JS
812}
813
356ee465
PW
814static char *get_author(const char *message)
815{
816 size_t len;
817 const char *a;
818
819 a = find_commit_header(message, "author", &len);
820 if (a)
821 return xmemdupz(a, len);
822
823 return NULL;
824}
825
d87d48b2
JS
826/* Read author-script and return an ident line (author <email> timestamp) */
827static const char *read_author_ident(struct strbuf *buf)
828{
67f16e3d 829 struct strbuf out = STRBUF_INIT;
4d010a75 830 char *name, *email, *date;
d87d48b2 831
4d010a75
PW
832 if (read_author_script(rebase_path_author_script(),
833 &name, &email, &date, 0))
d87d48b2
JS
834 return NULL;
835
5522bbac 836 /* validate date since fmt_ident() will die() on bad value */
4d010a75 837 if (parse_date(date, &out)){
5522bbac 838 warning(_("invalid date format '%s' in '%s'"),
4d010a75 839 date, rebase_path_author_script());
5522bbac
ES
840 strbuf_release(&out);
841 return NULL;
842 }
843
844 strbuf_reset(&out);
39ab4d09 845 strbuf_addstr(&out, fmt_ident(name, email, WANT_AUTHOR_IDENT, date, 0));
67f16e3d
ES
846 strbuf_swap(buf, &out);
847 strbuf_release(&out);
4d010a75
PW
848 free(name);
849 free(email);
850 free(date);
d87d48b2
JS
851 return buf->buf;
852}
853
791eb870
JS
854static const char staged_changes_advice[] =
855N_("you have staged changes in your working tree\n"
856"If these changes are meant to be squashed into the previous commit, run:\n"
857"\n"
858" git commit --amend %s\n"
859"\n"
860"If they are meant to go into a new commit, run:\n"
861"\n"
862" git commit %s\n"
863"\n"
864"In both cases, once you're done, continue with:\n"
865"\n"
866" git rebase --continue\n");
867
789b3eff
JS
868#define ALLOW_EMPTY (1<<0)
869#define EDIT_MSG (1<<1)
870#define AMEND_MSG (1<<2)
871#define CLEANUP_MSG (1<<3)
b92ff6e8 872#define VERIFY_MSG (1<<4)
d87d48b2 873#define CREATE_ROOT_COMMIT (1<<5)
789b3eff 874
34bec2c4
AG
875static int run_command_silent_on_success(struct child_process *cmd)
876{
877 struct strbuf buf = STRBUF_INIT;
878 int rc;
879
880 cmd->stdout_to_stderr = 1;
881 rc = pipe_command(cmd,
882 NULL, 0,
883 NULL, 0,
884 &buf, 0);
885
886 if (rc)
887 fputs(buf.buf, stderr);
888 strbuf_release(&buf);
889 return rc;
890}
891
043a4492
RR
892/*
893 * If we are cherry-pick, and if the merge did not result in
894 * hand-editing, we will hit this commit and inherit the original
895 * author date and name.
b5a67045 896 *
043a4492
RR
897 * If we are revert, or if our cherry-pick results in a hand merge,
898 * we had better say that the current user is responsible for that.
b5a67045
JS
899 *
900 * An exception is when run_git_commit() is called during an
901 * interactive rebase: in that case, we will want to retain the
902 * author metadata.
043a4492 903 */
f11c9580
NTND
904static int run_git_commit(struct repository *r,
905 const char *defmsg,
906 struct replay_opts *opts,
789b3eff 907 unsigned int flags)
043a4492 908{
07d968ef 909 struct child_process cmd = CHILD_PROCESS_INIT;
17d65f03 910 const char *value;
b27cfb0d 911
76fda6eb 912 if ((flags & CREATE_ROOT_COMMIT) && !(flags & AMEND_MSG)) {
d87d48b2 913 struct strbuf msg = STRBUF_INIT, script = STRBUF_INIT;
5dfcfe1e 914 const char *author = NULL;
d87d48b2
JS
915 struct object_id root_commit, *cache_tree_oid;
916 int res = 0;
917
5dfcfe1e
PW
918 if (is_rebase_i(opts)) {
919 author = read_author_ident(&script);
920 if (!author) {
921 strbuf_release(&script);
922 return -1;
923 }
924 }
925
d87d48b2
JS
926 if (!defmsg)
927 BUG("root commit without message");
928
f11c9580 929 if (!(cache_tree_oid = get_cache_tree_oid(r->index)))
d87d48b2
JS
930 res = -1;
931
932 if (!res)
933 res = strbuf_read_file(&msg, defmsg, 0);
934
935 if (res <= 0)
936 res = error_errno(_("could not read '%s'"), defmsg);
937 else
938 res = commit_tree(msg.buf, msg.len, cache_tree_oid,
939 NULL, &root_commit, author,
940 opts->gpg_sign);
941
942 strbuf_release(&msg);
943 strbuf_release(&script);
944 if (!res) {
945 update_ref(NULL, "CHERRY_PICK_HEAD", &root_commit, NULL,
946 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR);
947 res = update_ref(NULL, "HEAD", &root_commit, NULL, 0,
948 UPDATE_REFS_MSG_ON_ERR);
949 }
950 return res < 0 ? error(_("writing root commit")) : 0;
951 }
952
07d968ef
JS
953 cmd.git_cmd = 1;
954
34bec2c4
AG
955 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
956 const char *gpg_opt = gpg_sign_opt_quoted(opts);
a1c75762 957
34bec2c4
AG
958 return error(_(staged_changes_advice),
959 gpg_opt, gpg_opt);
b5a67045
JS
960 }
961
07d968ef 962 argv_array_push(&cmd.args, "commit");
043a4492 963
b92ff6e8
JS
964 if (!(flags & VERIFY_MSG))
965 argv_array_push(&cmd.args, "-n");
789b3eff 966 if ((flags & AMEND_MSG))
07d968ef 967 argv_array_push(&cmd.args, "--amend");
3bdd5522 968 if (opts->gpg_sign)
07d968ef 969 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
b5a67045 970 if (defmsg)
07d968ef 971 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
dc4b5bc3
JS
972 else if (!(flags & EDIT_MSG))
973 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
789b3eff 974 if ((flags & CLEANUP_MSG))
07d968ef 975 argv_array_push(&cmd.args, "--cleanup=strip");
789b3eff 976 if ((flags & EDIT_MSG))
07d968ef 977 argv_array_push(&cmd.args, "-e");
789b3eff 978 else if (!(flags & CLEANUP_MSG) &&
0009426d 979 !opts->signoff && !opts->record_origin &&
b5a67045 980 git_config_get_value("commit.cleanup", &value))
07d968ef 981 argv_array_push(&cmd.args, "--cleanup=verbatim");
b27cfb0d 982
789b3eff 983 if ((flags & ALLOW_EMPTY))
07d968ef 984 argv_array_push(&cmd.args, "--allow-empty");
df478b74 985
a3ec9eaf 986 if (!(flags & EDIT_MSG))
07d968ef 987 argv_array_push(&cmd.args, "--allow-empty-message");
4bee9584 988
34bec2c4
AG
989 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
990 return run_command_silent_on_success(&cmd);
991 else
992 return run_command(&cmd);
b27cfb0d
NH
993}
994
d0aaa46f
PW
995static int rest_is_empty(const struct strbuf *sb, int start)
996{
997 int i, eol;
998 const char *nl;
999
1000 /* Check if the rest is just whitespace and Signed-off-by's. */
1001 for (i = start; i < sb->len; i++) {
1002 nl = memchr(sb->buf + i, '\n', sb->len - i);
1003 if (nl)
1004 eol = nl - sb->buf;
1005 else
1006 eol = sb->len;
1007
1008 if (strlen(sign_off_header) <= eol - i &&
1009 starts_with(sb->buf + i, sign_off_header)) {
1010 i = eol;
1011 continue;
1012 }
1013 while (i < eol)
1014 if (!isspace(sb->buf[i++]))
1015 return 0;
1016 }
1017
1018 return 1;
1019}
1020
1021/*
1022 * Find out if the message in the strbuf contains only whitespace and
1023 * Signed-off-by lines.
1024 */
1025int message_is_empty(const struct strbuf *sb,
1026 enum commit_msg_cleanup_mode cleanup_mode)
1027{
1028 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1029 return 0;
1030 return rest_is_empty(sb, 0);
1031}
1032
1033/*
1034 * See if the user edited the message in the editor or left what
1035 * was in the template intact
1036 */
1037int template_untouched(const struct strbuf *sb, const char *template_file,
1038 enum commit_msg_cleanup_mode cleanup_mode)
1039{
1040 struct strbuf tmpl = STRBUF_INIT;
1041 const char *start;
1042
1043 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1044 return 0;
1045
1046 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1047 return 0;
1048
1049 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1050 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1051 start = sb->buf;
1052 strbuf_release(&tmpl);
1053 return rest_is_empty(sb, start - sb->buf);
1054}
1055
0505d604
PW
1056int update_head_with_reflog(const struct commit *old_head,
1057 const struct object_id *new_head,
1058 const char *action, const struct strbuf *msg,
1059 struct strbuf *err)
1060{
1061 struct ref_transaction *transaction;
1062 struct strbuf sb = STRBUF_INIT;
1063 const char *nl;
1064 int ret = 0;
1065
1066 if (action) {
1067 strbuf_addstr(&sb, action);
1068 strbuf_addstr(&sb, ": ");
1069 }
1070
1071 nl = strchr(msg->buf, '\n');
1072 if (nl) {
1073 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1074 } else {
1075 strbuf_addbuf(&sb, msg);
1076 strbuf_addch(&sb, '\n');
1077 }
1078
1079 transaction = ref_transaction_begin(err);
1080 if (!transaction ||
1081 ref_transaction_update(transaction, "HEAD", new_head,
1082 old_head ? &old_head->object.oid : &null_oid,
1083 0, sb.buf, err) ||
1084 ref_transaction_commit(transaction, err)) {
1085 ret = -1;
1086 }
1087 ref_transaction_free(transaction);
1088 strbuf_release(&sb);
1089
1090 return ret;
1091}
1092
a87a6f3c
PW
1093static int run_rewrite_hook(const struct object_id *oldoid,
1094 const struct object_id *newoid)
1095{
1096 struct child_process proc = CHILD_PROCESS_INIT;
1097 const char *argv[3];
1098 int code;
1099 struct strbuf sb = STRBUF_INIT;
1100
1101 argv[0] = find_hook("post-rewrite");
1102 if (!argv[0])
1103 return 0;
1104
1105 argv[1] = "amend";
1106 argv[2] = NULL;
1107
1108 proc.argv = argv;
1109 proc.in = -1;
1110 proc.stdout_to_stderr = 1;
6206286e 1111 proc.trace2_hook_name = "post-rewrite";
a87a6f3c
PW
1112
1113 code = start_command(&proc);
1114 if (code)
1115 return code;
1116 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1117 sigchain_push(SIGPIPE, SIG_IGN);
1118 write_in_full(proc.in, sb.buf, sb.len);
1119 close(proc.in);
1120 strbuf_release(&sb);
1121 sigchain_pop(SIGPIPE);
1122 return finish_command(&proc);
1123}
1124
1d18d758
NTND
1125void commit_post_rewrite(struct repository *r,
1126 const struct commit *old_head,
a87a6f3c
PW
1127 const struct object_id *new_head)
1128{
1129 struct notes_rewrite_cfg *cfg;
1130
1131 cfg = init_copy_notes_for_rewrite("amend");
1132 if (cfg) {
1133 /* we are amending, so old_head is not NULL */
1134 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1d18d758 1135 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
a87a6f3c
PW
1136 }
1137 run_rewrite_hook(&old_head->object.oid, new_head);
1138}
1139
f11c9580
NTND
1140static int run_prepare_commit_msg_hook(struct repository *r,
1141 struct strbuf *msg,
1142 const char *commit)
66618a50
PW
1143{
1144 struct argv_array hook_env = ARGV_ARRAY_INIT;
1145 int ret;
1146 const char *name;
1147
1148 name = git_path_commit_editmsg();
1149 if (write_message(msg->buf, msg->len, name, 0))
1150 return -1;
1151
f11c9580 1152 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", r->index_file);
66618a50
PW
1153 argv_array_push(&hook_env, "GIT_EDITOR=:");
1154 if (commit)
1155 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1156 "commit", commit, NULL);
1157 else
1158 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1159 "message", NULL);
1160 if (ret)
1161 ret = error(_("'prepare-commit-msg' hook failed"));
1162 argv_array_clear(&hook_env);
1163
1164 return ret;
1165}
1166
e47c6caf
PW
1167static const char implicit_ident_advice_noconfig[] =
1168N_("Your name and email address were configured automatically based\n"
1169"on your username and hostname. Please check that they are accurate.\n"
1170"You can suppress this message by setting them explicitly. Run the\n"
1171"following command and follow the instructions in your editor to edit\n"
1172"your configuration file:\n"
1173"\n"
1174" git config --global --edit\n"
1175"\n"
1176"After doing this, you may fix the identity used for this commit with:\n"
1177"\n"
1178" git commit --amend --reset-author\n");
1179
1180static const char implicit_ident_advice_config[] =
1181N_("Your name and email address were configured automatically based\n"
1182"on your username and hostname. Please check that they are accurate.\n"
1183"You can suppress this message by setting them explicitly:\n"
1184"\n"
1185" git config --global user.name \"Your Name\"\n"
1186" git config --global user.email you@example.com\n"
1187"\n"
1188"After doing this, you may fix the identity used for this commit with:\n"
1189"\n"
1190" git commit --amend --reset-author\n");
1191
1192static const char *implicit_ident_advice(void)
1193{
1194 char *user_config = expand_user_path("~/.gitconfig", 0);
1195 char *xdg_config = xdg_config_home("config");
1196 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1197
1198 free(user_config);
1199 free(xdg_config);
1200
1201 if (config_exists)
1202 return _(implicit_ident_advice_config);
1203 else
1204 return _(implicit_ident_advice_noconfig);
1205
1206}
1207
f11c9580
NTND
1208void print_commit_summary(struct repository *r,
1209 const char *prefix,
1210 const struct object_id *oid,
e47c6caf
PW
1211 unsigned int flags)
1212{
1213 struct rev_info rev;
1214 struct commit *commit;
1215 struct strbuf format = STRBUF_INIT;
1216 const char *head;
1217 struct pretty_print_context pctx = {0};
1218 struct strbuf author_ident = STRBUF_INIT;
1219 struct strbuf committer_ident = STRBUF_INIT;
1220
f11c9580 1221 commit = lookup_commit(r, oid);
e47c6caf
PW
1222 if (!commit)
1223 die(_("couldn't look up newly created commit"));
1224 if (parse_commit(commit))
1225 die(_("could not parse newly created commit"));
1226
1227 strbuf_addstr(&format, "format:%h] %s");
1228
1229 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1230 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1231 if (strbuf_cmp(&author_ident, &committer_ident)) {
1232 strbuf_addstr(&format, "\n Author: ");
1233 strbuf_addbuf_percentquote(&format, &author_ident);
1234 }
1235 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1236 struct strbuf date = STRBUF_INIT;
1237
1238 format_commit_message(commit, "%ad", &date, &pctx);
1239 strbuf_addstr(&format, "\n Date: ");
1240 strbuf_addbuf_percentquote(&format, &date);
1241 strbuf_release(&date);
1242 }
1243 if (!committer_ident_sufficiently_given()) {
1244 strbuf_addstr(&format, "\n Committer: ");
1245 strbuf_addbuf_percentquote(&format, &committer_ident);
1246 if (advice_implicit_identity) {
1247 strbuf_addch(&format, '\n');
1248 strbuf_addstr(&format, implicit_ident_advice());
1249 }
1250 }
1251 strbuf_release(&author_ident);
1252 strbuf_release(&committer_ident);
1253
f11c9580 1254 repo_init_revisions(r, &rev, prefix);
e47c6caf
PW
1255 setup_revisions(0, NULL, &rev, NULL);
1256
1257 rev.diff = 1;
1258 rev.diffopt.output_format =
1259 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1260
1261 rev.verbose_header = 1;
1262 rev.show_root_diff = 1;
1263 get_commit_format(format.buf, &rev);
1264 rev.always_show_header = 0;
0f57f731 1265 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
e47c6caf
PW
1266 rev.diffopt.break_opt = 0;
1267 diff_setup_done(&rev.diffopt);
1268
1269 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1270 if (!head)
1271 die_errno(_("unable to resolve HEAD after creating commit"));
1272 if (!strcmp(head, "HEAD"))
1273 head = _("detached HEAD");
1274 else
1275 skip_prefix(head, "refs/heads/", &head);
1276 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1277 _(" (root-commit)") : "");
1278
1279 if (!log_tree_commit(&rev, commit)) {
1280 rev.always_show_header = 1;
1281 rev.use_terminator = 1;
1282 log_tree_commit(&rev, commit);
1283 }
1284
1285 strbuf_release(&format);
1286}
1287
005af339 1288static int parse_head(struct repository *r, struct commit **head)
356ee465
PW
1289{
1290 struct commit *current_head;
1291 struct object_id oid;
1292
1293 if (get_oid("HEAD", &oid)) {
1294 current_head = NULL;
1295 } else {
005af339 1296 current_head = lookup_commit_reference(r, &oid);
356ee465
PW
1297 if (!current_head)
1298 return error(_("could not parse HEAD"));
9001dc2a 1299 if (!oideq(&oid, &current_head->object.oid)) {
356ee465
PW
1300 warning(_("HEAD %s is not a commit!"),
1301 oid_to_hex(&oid));
1302 }
1303 if (parse_commit(current_head))
1304 return error(_("could not parse HEAD commit"));
1305 }
1306 *head = current_head;
1307
1308 return 0;
1309}
1310
1311/*
1312 * Try to commit without forking 'git commit'. In some cases we need
1313 * to run 'git commit' to display an error message
1314 *
1315 * Returns:
1316 * -1 - error unable to commit
1317 * 0 - success
1318 * 1 - run 'git commit'
1319 */
f11c9580
NTND
1320static int try_to_commit(struct repository *r,
1321 struct strbuf *msg, const char *author,
356ee465
PW
1322 struct replay_opts *opts, unsigned int flags,
1323 struct object_id *oid)
1324{
1325 struct object_id tree;
1326 struct commit *current_head;
1327 struct commit_list *parents = NULL;
1328 struct commit_extra_header *extra = NULL;
1329 struct strbuf err = STRBUF_INIT;
66618a50 1330 struct strbuf commit_msg = STRBUF_INIT;
356ee465 1331 char *amend_author = NULL;
66618a50 1332 const char *hook_commit = NULL;
356ee465
PW
1333 enum commit_msg_cleanup_mode cleanup;
1334 int res = 0;
1335
005af339 1336 if (parse_head(r, &current_head))
356ee465
PW
1337 return -1;
1338
1339 if (flags & AMEND_MSG) {
1340 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1341 const char *out_enc = get_commit_output_encoding();
1342 const char *message = logmsg_reencode(current_head, NULL,
1343 out_enc);
1344
1345 if (!msg) {
1346 const char *orig_message = NULL;
1347
1348 find_commit_subject(message, &orig_message);
66618a50 1349 msg = &commit_msg;
356ee465 1350 strbuf_addstr(msg, orig_message);
66618a50 1351 hook_commit = "HEAD";
356ee465
PW
1352 }
1353 author = amend_author = get_author(message);
1354 unuse_commit_buffer(current_head, message);
1355 if (!author) {
1356 res = error(_("unable to parse commit author"));
1357 goto out;
1358 }
1359 parents = copy_commit_list(current_head->parents);
1360 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1361 } else if (current_head) {
1362 commit_list_insert(current_head, &parents);
1363 }
1364
f11c9580 1365 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
356ee465
PW
1366 res = error(_("git write-tree failed to write a tree"));
1367 goto out;
1368 }
1369
4a7e27e9
JK
1370 if (!(flags & ALLOW_EMPTY) && oideq(current_head ?
1371 get_commit_tree_oid(current_head) :
1372 the_hash_algo->empty_tree, &tree)) {
356ee465
PW
1373 res = 1; /* run 'git commit' to display error message */
1374 goto out;
1375 }
1376
66618a50 1377 if (find_hook("prepare-commit-msg")) {
f11c9580 1378 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
66618a50
PW
1379 if (res)
1380 goto out;
1381 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1382 2048) < 0) {
1383 res = error_errno(_("unable to read commit message "
1384 "from '%s'"),
1385 git_path_commit_editmsg());
1386 goto out;
1387 }
1388 msg = &commit_msg;
1389 }
1390
d74f3e58
PW
1391 if (flags & CLEANUP_MSG)
1392 cleanup = COMMIT_MSG_CLEANUP_ALL;
1393 else if ((opts->signoff || opts->record_origin) &&
1394 !opts->explicit_cleanup)
1395 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1396 else
1397 cleanup = opts->default_msg_cleanup;
66618a50
PW
1398
1399 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1400 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
a3ec9eaf 1401 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
66618a50
PW
1402 res = 1; /* run 'git commit' to display error message */
1403 goto out;
1404 }
1405
12f7babd
JS
1406 reset_ident_date();
1407
8be8342b
JH
1408 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1409 oid, author, opts->gpg_sign, extra)) {
356ee465
PW
1410 res = error(_("failed to write commit object"));
1411 goto out;
1412 }
1413
1414 if (update_head_with_reflog(current_head, oid,
1415 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1416 res = error("%s", err.buf);
1417 goto out;
1418 }
1419
1420 if (flags & AMEND_MSG)
1d18d758 1421 commit_post_rewrite(r, current_head, oid);
356ee465
PW
1422
1423out:
1424 free_commit_extra_headers(extra);
1425 strbuf_release(&err);
66618a50 1426 strbuf_release(&commit_msg);
356ee465
PW
1427 free(amend_author);
1428
1429 return res;
1430}
1431
f11c9580
NTND
1432static int do_commit(struct repository *r,
1433 const char *msg_file, const char *author,
356ee465
PW
1434 struct replay_opts *opts, unsigned int flags)
1435{
1436 int res = 1;
1437
d87d48b2
JS
1438 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG) &&
1439 !(flags & CREATE_ROOT_COMMIT)) {
356ee465
PW
1440 struct object_id oid;
1441 struct strbuf sb = STRBUF_INIT;
1442
1443 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1444 return error_errno(_("unable to read commit message "
1445 "from '%s'"),
1446 msg_file);
1447
f11c9580
NTND
1448 res = try_to_commit(r, msg_file ? &sb : NULL,
1449 author, opts, flags, &oid);
356ee465
PW
1450 strbuf_release(&sb);
1451 if (!res) {
f11c9580
NTND
1452 unlink(git_path_cherry_pick_head(r));
1453 unlink(git_path_merge_msg(r));
356ee465 1454 if (!is_rebase_i(opts))
f11c9580 1455 print_commit_summary(r, NULL, &oid,
356ee465
PW
1456 SUMMARY_SHOW_AUTHOR_DATE);
1457 return res;
1458 }
1459 }
1460 if (res == 1)
f11c9580 1461 return run_git_commit(r, msg_file, opts, flags);
356ee465
PW
1462
1463 return res;
1464}
1465
b27cfb0d
NH
1466static int is_original_commit_empty(struct commit *commit)
1467{
092bbcdf 1468 const struct object_id *ptree_oid;
b27cfb0d
NH
1469
1470 if (parse_commit(commit))
aee42e1f 1471 return error(_("could not parse commit %s"),
f2fd0760 1472 oid_to_hex(&commit->object.oid));
b27cfb0d
NH
1473 if (commit->parents) {
1474 struct commit *parent = commit->parents->item;
1475 if (parse_commit(parent))
aee42e1f 1476 return error(_("could not parse parent commit %s"),
f2fd0760 1477 oid_to_hex(&parent->object.oid));
2e27bd77 1478 ptree_oid = get_commit_tree_oid(parent);
b27cfb0d 1479 } else {
eb0ccfd7 1480 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
043a4492 1481 }
043a4492 1482
4a7e27e9 1483 return oideq(ptree_oid, get_commit_tree_oid(commit));
043a4492
RR
1484}
1485
ac2b0e8f
JH
1486/*
1487 * Do we run "git commit" with "--allow-empty"?
1488 */
f11c9580
NTND
1489static int allow_empty(struct repository *r,
1490 struct replay_opts *opts,
1491 struct commit *commit)
ac2b0e8f
JH
1492{
1493 int index_unchanged, empty_commit;
1494
1495 /*
1496 * Three cases:
1497 *
1498 * (1) we do not allow empty at all and error out.
1499 *
1500 * (2) we allow ones that were initially empty, but
1501 * forbid the ones that become empty;
1502 *
1503 * (3) we allow both.
1504 */
1505 if (!opts->allow_empty)
1506 return 0; /* let "git commit" barf as necessary */
1507
005af339 1508 index_unchanged = is_index_unchanged(r);
ac2b0e8f
JH
1509 if (index_unchanged < 0)
1510 return index_unchanged;
1511 if (!index_unchanged)
1512 return 0; /* we do not have to say --allow-empty */
1513
1514 if (opts->keep_redundant_commits)
1515 return 1;
1516
1517 empty_commit = is_original_commit_empty(commit);
1518 if (empty_commit < 0)
1519 return empty_commit;
1520 if (!empty_commit)
1521 return 0;
1522 else
1523 return 1;
1524}
1525
25c43667
JS
1526/*
1527 * Note that ordering matters in this enum. Not only must it match the mapping
1528 * below, it is also divided into several sections that matter. When adding
1529 * new commands, make sure you add it in the right section.
1530 */
004fefa7 1531enum todo_command {
25c43667 1532 /* commands that handle commits */
004fefa7 1533 TODO_PICK = 0,
25c43667 1534 TODO_REVERT,
56dc3ab0 1535 TODO_EDIT,
04efc8b5 1536 TODO_REWORD,
6e98de72
JS
1537 TODO_FIXUP,
1538 TODO_SQUASH,
311af526
JS
1539 /* commands that do something else than handling a single commit */
1540 TODO_EXEC,
71f82465 1541 TODO_BREAK,
9055e401
JS
1542 TODO_LABEL,
1543 TODO_RESET,
4c68e7dd 1544 TODO_MERGE,
25c43667 1545 /* commands that do nothing but are counted for reporting progress */
b3fdd581 1546 TODO_NOOP,
ac191470
JS
1547 TODO_DROP,
1548 /* comments (not counted for reporting progress) */
1549 TODO_COMMENT
004fefa7
JS
1550};
1551
414697a9
JS
1552static struct {
1553 char c;
1554 const char *str;
1555} todo_command_info[] = {
1556 { 'p', "pick" },
1557 { 0, "revert" },
1558 { 'e', "edit" },
04efc8b5 1559 { 'r', "reword" },
414697a9
JS
1560 { 'f', "fixup" },
1561 { 's', "squash" },
1562 { 'x', "exec" },
71f82465 1563 { 'b', "break" },
9055e401
JS
1564 { 'l', "label" },
1565 { 't', "reset" },
4c68e7dd 1566 { 'm', "merge" },
b3fdd581 1567 { 0, "noop" },
ac191470
JS
1568 { 'd', "drop" },
1569 { 0, NULL }
004fefa7
JS
1570};
1571
1572static const char *command_to_string(const enum todo_command command)
1573{
ac191470 1574 if (command < TODO_COMMENT)
414697a9 1575 return todo_command_info[command].str;
02127c63 1576 die(_("unknown command: %d"), command);
004fefa7
JS
1577}
1578
ee5462d6 1579static char command_to_char(const enum todo_command command)
d8ae6c84
LB
1580{
1581 if (command < TODO_COMMENT && todo_command_info[command].c)
1582 return todo_command_info[command].c;
1583 return comment_line_char;
1584}
1585
25c43667
JS
1586static int is_noop(const enum todo_command command)
1587{
b3fdd581 1588 return TODO_NOOP <= command;
25c43667 1589}
004fefa7 1590
6e98de72
JS
1591static int is_fixup(enum todo_command command)
1592{
1593 return command == TODO_FIXUP || command == TODO_SQUASH;
1594}
1595
d87d48b2
JS
1596/* Does this command create a (non-merge) commit? */
1597static int is_pick_or_similar(enum todo_command command)
1598{
1599 switch (command) {
1600 case TODO_PICK:
1601 case TODO_REVERT:
1602 case TODO_EDIT:
1603 case TODO_REWORD:
1604 case TODO_FIXUP:
1605 case TODO_SQUASH:
1606 return 1;
1607 default:
1608 return 0;
1609 }
1610}
1611
005af339
NTND
1612static int update_squash_messages(struct repository *r,
1613 enum todo_command command,
1614 struct commit *commit,
1615 struct replay_opts *opts)
6e98de72
JS
1616{
1617 struct strbuf buf = STRBUF_INIT;
e12a7ef5 1618 int res;
6e98de72
JS
1619 const char *message, *body;
1620
e12a7ef5 1621 if (opts->current_fixup_count > 0) {
6e98de72 1622 struct strbuf header = STRBUF_INIT;
e12a7ef5 1623 char *eol;
6e98de72 1624
e12a7ef5 1625 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
6e98de72
JS
1626 return error(_("could not read '%s'"),
1627 rebase_path_squash_msg());
1628
e12a7ef5
JS
1629 eol = buf.buf[0] != comment_line_char ?
1630 buf.buf : strchrnul(buf.buf, '\n');
6e98de72
JS
1631
1632 strbuf_addf(&header, "%c ", comment_line_char);
e12a7ef5
JS
1633 strbuf_addf(&header, _("This is a combination of %d commits."),
1634 opts->current_fixup_count + 2);
6e98de72
JS
1635 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1636 strbuf_release(&header);
1637 } else {
33d66df3 1638 struct object_id head;
6e98de72
JS
1639 struct commit *head_commit;
1640 const char *head_message, *body;
1641
33d66df3 1642 if (get_oid("HEAD", &head))
6e98de72 1643 return error(_("need a HEAD to fixup"));
005af339 1644 if (!(head_commit = lookup_commit_reference(r, &head)))
6e98de72
JS
1645 return error(_("could not read HEAD"));
1646 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1647 return error(_("could not read HEAD's commit message"));
1648
1649 find_commit_subject(head_message, &body);
1650 if (write_message(body, strlen(body),
1651 rebase_path_fixup_msg(), 0)) {
1652 unuse_commit_buffer(head_commit, head_message);
1653 return error(_("cannot write '%s'"),
1654 rebase_path_fixup_msg());
1655 }
1656
6e98de72 1657 strbuf_addf(&buf, "%c ", comment_line_char);
e12a7ef5 1658 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
6e98de72
JS
1659 strbuf_addf(&buf, "\n%c ", comment_line_char);
1660 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1661 strbuf_addstr(&buf, "\n\n");
1662 strbuf_addstr(&buf, body);
1663
1664 unuse_commit_buffer(head_commit, head_message);
1665 }
1666
1667 if (!(message = get_commit_buffer(commit, NULL)))
1668 return error(_("could not read commit message of %s"),
1669 oid_to_hex(&commit->object.oid));
1670 find_commit_subject(message, &body);
1671
1672 if (command == TODO_SQUASH) {
1673 unlink(rebase_path_fixup_msg());
1674 strbuf_addf(&buf, "\n%c ", comment_line_char);
e12a7ef5 1675 strbuf_addf(&buf, _("This is the commit message #%d:"),
dd2e36eb 1676 ++opts->current_fixup_count + 1);
6e98de72
JS
1677 strbuf_addstr(&buf, "\n\n");
1678 strbuf_addstr(&buf, body);
1679 } else if (command == TODO_FIXUP) {
1680 strbuf_addf(&buf, "\n%c ", comment_line_char);
1681 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
dd2e36eb 1682 ++opts->current_fixup_count + 1);
6e98de72
JS
1683 strbuf_addstr(&buf, "\n\n");
1684 strbuf_add_commented_lines(&buf, body, strlen(body));
1685 } else
1686 return error(_("unknown command: %d"), command);
1687 unuse_commit_buffer(commit, message);
1688
1689 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1690 strbuf_release(&buf);
e12a7ef5
JS
1691
1692 if (!res) {
1693 strbuf_addf(&opts->current_fixups, "%s%s %s",
1694 opts->current_fixups.len ? "\n" : "",
1695 command_to_string(command),
1696 oid_to_hex(&commit->object.oid));
1697 res = write_message(opts->current_fixups.buf,
1698 opts->current_fixups.len,
1699 rebase_path_current_fixups(), 0);
1700 }
1701
6e98de72
JS
1702 return res;
1703}
1704
3b335762
NTND
1705static void flush_rewritten_pending(void)
1706{
25cb8df9 1707 struct strbuf buf = STRBUF_INIT;
092bbcdf 1708 struct object_id newoid;
25cb8df9
JS
1709 FILE *out;
1710
092bbcdf 1711 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1712 !get_oid("HEAD", &newoid) &&
e9d983f1 1713 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
25cb8df9
JS
1714 char *bol = buf.buf, *eol;
1715
1716 while (*bol) {
1717 eol = strchrnul(bol, '\n');
1718 fprintf(out, "%.*s %s\n", (int)(eol - bol),
092bbcdf 1719 bol, oid_to_hex(&newoid));
25cb8df9
JS
1720 if (!*eol)
1721 break;
1722 bol = eol + 1;
1723 }
1724 fclose(out);
1725 unlink(rebase_path_rewritten_pending());
1726 }
1727 strbuf_release(&buf);
1728}
1729
1730static void record_in_rewritten(struct object_id *oid,
3b335762
NTND
1731 enum todo_command next_command)
1732{
e9d983f1 1733 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
25cb8df9
JS
1734
1735 if (!out)
1736 return;
1737
1738 fprintf(out, "%s\n", oid_to_hex(oid));
1739 fclose(out);
1740
1741 if (!is_fixup(next_command))
1742 flush_rewritten_pending();
1743}
1744
f11c9580
NTND
1745static int do_pick_commit(struct repository *r,
1746 enum todo_command command,
1747 struct commit *commit,
1748 struct replay_opts *opts,
1749 int final_fixup)
043a4492 1750{
789b3eff 1751 unsigned int flags = opts->edit ? EDIT_MSG : 0;
f11c9580 1752 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
ace976b2 1753 struct object_id head;
043a4492
RR
1754 struct commit *base, *next, *parent;
1755 const char *base_label, *next_label;
356ee465 1756 char *author = NULL;
d74a4e57 1757 struct commit_message msg = { NULL, NULL, NULL, NULL };
043a4492 1758 struct strbuf msgbuf = STRBUF_INIT;
789b3eff 1759 int res, unborn = 0, allow;
043a4492
RR
1760
1761 if (opts->no_commit) {
1762 /*
1763 * We do not intend to commit immediately. We just want to
1764 * merge the differences in, so let's compute the tree
1765 * that represents the "current" state for merge-recursive
1766 * to work on.
1767 */
f11c9580 1768 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
93b3df6f 1769 return error(_("your index file is unmerged."));
043a4492 1770 } else {
ace976b2 1771 unborn = get_oid("HEAD", &head);
d87d48b2
JS
1772 /* Do we want to generate a root commit? */
1773 if (is_pick_or_similar(command) && opts->have_squash_onto &&
4a7e27e9 1774 oideq(&head, &opts->squash_onto)) {
d87d48b2
JS
1775 if (is_fixup(command))
1776 return error(_("cannot fixup root commit"));
1777 flags |= CREATE_ROOT_COMMIT;
1778 unborn = 1;
1779 } else if (unborn)
eb0ccfd7 1780 oidcpy(&head, the_hash_algo->empty_tree);
ffc00a48 1781 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
02f2f56b 1782 NULL, 0))
e1ff0a32 1783 return error_dirty_index(r, opts);
043a4492 1784 }
f11c9580 1785 discard_index(r->index);
043a4492 1786
637666c8 1787 if (!commit->parents)
043a4492 1788 parent = NULL;
043a4492
RR
1789 else if (commit->parents->next) {
1790 /* Reverting or cherry-picking a merge commit */
1791 int cnt;
1792 struct commit_list *p;
1793
1794 if (!opts->mainline)
93b3df6f 1795 return error(_("commit %s is a merge but no -m option was given."),
f2fd0760 1796 oid_to_hex(&commit->object.oid));
043a4492
RR
1797
1798 for (cnt = 1, p = commit->parents;
1799 cnt != opts->mainline && p;
1800 cnt++)
1801 p = p->next;
1802 if (cnt != opts->mainline || !p)
93b3df6f 1803 return error(_("commit %s does not have parent %d"),
f2fd0760 1804 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492 1805 parent = p->item;
37897bfc
SO
1806 } else if (1 < opts->mainline)
1807 /*
1808 * Non-first parent explicitly specified as mainline for
1809 * non-merge commit
1810 */
1811 return error(_("commit %s does not have parent %d"),
1812 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492
RR
1813 else
1814 parent = commit->parents->item;
1815
bcbb68be
JS
1816 if (get_message(commit, &msg) != 0)
1817 return error(_("cannot get commit message for %s"),
1818 oid_to_hex(&commit->object.oid));
1819
6e98de72 1820 if (opts->allow_ff && !is_fixup(command) &&
4a7e27e9 1821 ((parent && oideq(&parent->object.oid, &head)) ||
bcbb68be
JS
1822 (!parent && unborn))) {
1823 if (is_rebase_i(opts))
1824 write_author_script(msg.message);
f11c9580 1825 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
bcbb68be
JS
1826 opts);
1827 if (res || command != TODO_REWORD)
1828 goto leave;
5f8f9277 1829 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
bcbb68be
JS
1830 msg_file = NULL;
1831 goto fast_forward_edit;
1832 }
043a4492 1833 if (parent && parse_commit(parent) < 0)
004fefa7
JS
1834 /* TRANSLATORS: The first %s will be a "todo" command like
1835 "revert" or "pick", the second %s a SHA1. */
043a4492 1836 return error(_("%s: cannot parse parent commit %s"),
004fefa7
JS
1837 command_to_string(command),
1838 oid_to_hex(&parent->object.oid));
043a4492 1839
043a4492
RR
1840 /*
1841 * "commit" is an existing commit. We would want to apply
1842 * the difference it introduces since its first parent "prev"
1843 * on top of the current HEAD if we are cherry-pick. Or the
1844 * reverse of it if we are revert.
1845 */
1846
004fefa7 1847 if (command == TODO_REVERT) {
043a4492
RR
1848 base = commit;
1849 base_label = msg.label;
1850 next = parent;
1851 next_label = msg.parent_label;
1852 strbuf_addstr(&msgbuf, "Revert \"");
1853 strbuf_addstr(&msgbuf, msg.subject);
1854 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
f2fd0760 1855 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
1856
1857 if (commit->parents && commit->parents->next) {
1858 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
f2fd0760 1859 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
043a4492
RR
1860 }
1861 strbuf_addstr(&msgbuf, ".\n");
1862 } else {
1863 const char *p;
1864
1865 base = parent;
1866 base_label = msg.parent_label;
1867 next = commit;
1868 next_label = msg.label;
1869
23aa5142
JS
1870 /* Append the commit log message to msgbuf. */
1871 if (find_commit_subject(msg.message, &p))
1872 strbuf_addstr(&msgbuf, p);
043a4492
RR
1873
1874 if (opts->record_origin) {
44dc738a 1875 strbuf_complete_line(&msgbuf);
bab4d109 1876 if (!has_conforming_footer(&msgbuf, NULL, 0))
b971e04f 1877 strbuf_addch(&msgbuf, '\n');
cd650a4e 1878 strbuf_addstr(&msgbuf, cherry_picked_prefix);
f2fd0760 1879 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
1880 strbuf_addstr(&msgbuf, ")\n");
1881 }
356ee465
PW
1882 if (!is_fixup(command))
1883 author = get_author(msg.message);
043a4492
RR
1884 }
1885
04efc8b5 1886 if (command == TODO_REWORD)
b92ff6e8 1887 flags |= EDIT_MSG | VERIFY_MSG;
04efc8b5 1888 else if (is_fixup(command)) {
005af339 1889 if (update_squash_messages(r, command, commit, opts))
6e98de72 1890 return -1;
789b3eff 1891 flags |= AMEND_MSG;
6e98de72
JS
1892 if (!final_fixup)
1893 msg_file = rebase_path_squash_msg();
1894 else if (file_exists(rebase_path_fixup_msg())) {
789b3eff 1895 flags |= CLEANUP_MSG;
6e98de72
JS
1896 msg_file = rebase_path_fixup_msg();
1897 } else {
f11c9580 1898 const char *dest = git_path_squash_msg(r);
6e98de72
JS
1899 unlink(dest);
1900 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1901 return error(_("could not rename '%s' to '%s'"),
1902 rebase_path_squash_msg(), dest);
f11c9580 1903 unlink(git_path_merge_msg(r));
6e98de72 1904 msg_file = dest;
789b3eff 1905 flags |= EDIT_MSG;
6e98de72
JS
1906 }
1907 }
1908
a852ec7f 1909 if (opts->signoff && !is_fixup(command))
b34eeea3
PW
1910 append_signoff(&msgbuf, 0, 0);
1911
0473f28a
JS
1912 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1913 res = -1;
1914 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
f11c9580 1915 res = do_recursive_merge(r, base, next, base_label, next_label,
48be4c62 1916 &head, &msgbuf, opts);
f241ff0d 1917 if (res < 0)
19517fb9
SB
1918 goto leave;
1919
75871495 1920 res |= write_message(msgbuf.buf, msgbuf.len,
f11c9580 1921 git_path_merge_msg(r), 0);
043a4492
RR
1922 } else {
1923 struct commit_list *common = NULL;
1924 struct commit_list *remotes = NULL;
1925
75871495 1926 res = write_message(msgbuf.buf, msgbuf.len,
f11c9580 1927 git_path_merge_msg(r), 0);
043a4492
RR
1928
1929 commit_list_insert(base, &common);
1930 commit_list_insert(next, &remotes);
f11c9580 1931 res |= try_merge_command(r, opts->strategy,
03a4e260 1932 opts->xopts_nr, (const char **)opts->xopts,
ace976b2 1933 common, oid_to_hex(&head), remotes);
043a4492
RR
1934 free_commit_list(common);
1935 free_commit_list(remotes);
1936 }
452202c7 1937 strbuf_release(&msgbuf);
043a4492
RR
1938
1939 /*
1940 * If the merge was clean or if it failed due to conflict, we write
1941 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1942 * However, if the merge did not even start, then we don't want to
1943 * write it at all.
1944 */
004fefa7 1945 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
ae077771 1946 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
91774afc 1947 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 1948 res = -1;
004fefa7 1949 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
ae077771 1950 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
91774afc 1951 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 1952 res = -1;
043a4492
RR
1953
1954 if (res) {
004fefa7 1955 error(command == TODO_REVERT
043a4492
RR
1956 ? _("could not revert %s... %s")
1957 : _("could not apply %s... %s"),
39755964 1958 short_commit_name(commit), msg.subject);
005af339 1959 print_advice(r, res == 1, opts);
f11c9580 1960 repo_rerere(r, opts->allow_rerere_auto);
c8d1351d 1961 goto leave;
043a4492
RR
1962 }
1963
f11c9580 1964 allow = allow_empty(r, opts, commit);
706728a3
FC
1965 if (allow < 0) {
1966 res = allow;
1967 goto leave;
789b3eff
JS
1968 } else if (allow)
1969 flags |= ALLOW_EMPTY;
356ee465 1970 if (!opts->no_commit) {
bcbb68be 1971fast_forward_edit:
356ee465 1972 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
f11c9580 1973 res = do_commit(r, msg_file, author, opts, flags);
356ee465
PW
1974 else
1975 res = error(_("unable to parse commit author"));
1976 }
6e98de72
JS
1977
1978 if (!res && final_fixup) {
1979 unlink(rebase_path_fixup_msg());
1980 unlink(rebase_path_squash_msg());
e12a7ef5
JS
1981 unlink(rebase_path_current_fixups());
1982 strbuf_reset(&opts->current_fixups);
1983 opts->current_fixup_count = 0;
6e98de72 1984 }
c8d1351d
FC
1985
1986leave:
d74a4e57 1987 free_message(commit, &msg);
356ee465 1988 free(author);
1e41229d 1989 update_abort_safety_file();
043a4492
RR
1990
1991 return res;
1992}
1993
c3e8618c 1994static int prepare_revs(struct replay_opts *opts)
043a4492 1995{
a73e22e9
MZ
1996 /*
1997 * picking (but not reverting) ranges (but not individual revisions)
1998 * should be done in reverse
1999 */
2000 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
043a4492
RR
2001 opts->revs->reverse ^= 1;
2002
2003 if (prepare_revision_walk(opts->revs))
c3e8618c 2004 return error(_("revision walk setup failed"));
043a4492 2005
c3e8618c 2006 return 0;
043a4492
RR
2007}
2008
f11c9580
NTND
2009static int read_and_refresh_cache(struct repository *r,
2010 struct replay_opts *opts)
043a4492 2011{
14bca6c6 2012 struct lock_file index_lock = LOCK_INIT;
3a95f31d
NTND
2013 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2014 if (repo_read_index(r) < 0) {
49fb937e 2015 rollback_lock_file(&index_lock);
0d9c6dc9 2016 return error(_("git %s: failed to read the index"),
c28cbc5e 2017 _(action_name(opts)));
49fb937e 2018 }
f11c9580 2019 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
61000814 2020 if (index_fd >= 0) {
f11c9580 2021 if (write_locked_index(r->index, &index_lock,
61000814 2022 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
0d9c6dc9 2023 return error(_("git %s: failed to refresh the index"),
c28cbc5e 2024 _(action_name(opts)));
49fb937e 2025 }
043a4492 2026 }
0d9c6dc9 2027 return 0;
043a4492
RR
2028}
2029
4c68e7dd
JS
2030enum todo_item_flags {
2031 TODO_EDIT_MERGE_MSG = 1
2032};
2033
004fefa7
JS
2034struct todo_item {
2035 enum todo_command command;
2036 struct commit *commit;
4c68e7dd 2037 unsigned int flags;
c22f7dfb
JS
2038 const char *arg;
2039 int arg_len;
004fefa7
JS
2040 size_t offset_in_buf;
2041};
2042
2043struct todo_list {
2044 struct strbuf buf;
2045 struct todo_item *items;
2046 int nr, alloc, current;
968492e4 2047 int done_nr, total_nr;
54fd3243 2048 struct stat_data stat;
004fefa7
JS
2049};
2050
2051#define TODO_LIST_INIT { STRBUF_INIT }
2052
2053static void todo_list_release(struct todo_list *todo_list)
043a4492 2054{
004fefa7 2055 strbuf_release(&todo_list->buf);
6a83d902 2056 FREE_AND_NULL(todo_list->items);
004fefa7
JS
2057 todo_list->nr = todo_list->alloc = 0;
2058}
043a4492 2059
004fefa7
JS
2060static struct todo_item *append_new_todo(struct todo_list *todo_list)
2061{
2062 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2063 return todo_list->items + todo_list->nr++;
043a4492
RR
2064}
2065
005af339
NTND
2066static int parse_insn_line(struct repository *r, struct todo_item *item,
2067 const char *bol, char *eol)
043a4492 2068{
1e43ed98 2069 struct object_id commit_oid;
043a4492 2070 char *end_of_object_name;
004fefa7
JS
2071 int i, saved, status, padding;
2072
4c68e7dd
JS
2073 item->flags = 0;
2074
8f8550b3
JS
2075 /* left-trim */
2076 bol += strspn(bol, " \t");
2077
25c43667 2078 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
ac191470 2079 item->command = TODO_COMMENT;
25c43667
JS
2080 item->commit = NULL;
2081 item->arg = bol;
2082 item->arg_len = eol - bol;
2083 return 0;
2084 }
2085
ac191470 2086 for (i = 0; i < TODO_COMMENT; i++)
414697a9
JS
2087 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
2088 item->command = i;
2089 break;
3a4a4cab
JS
2090 } else if ((bol + 1 == eol || bol[1] == ' ') &&
2091 *bol == todo_command_info[i].c) {
414697a9 2092 bol++;
004fefa7
JS
2093 item->command = i;
2094 break;
2095 }
ac191470 2096 if (i >= TODO_COMMENT)
004fefa7 2097 return -1;
043a4492 2098
66afa24f
JS
2099 /* Eat up extra spaces/ tabs before object name */
2100 padding = strspn(bol, " \t");
2101 bol += padding;
2102
71f82465 2103 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
66afa24f
JS
2104 if (bol != eol)
2105 return error(_("%s does not accept arguments: '%s'"),
2106 command_to_string(item->command), bol);
25c43667
JS
2107 item->commit = NULL;
2108 item->arg = bol;
2109 item->arg_len = eol - bol;
2110 return 0;
2111 }
2112
043a4492 2113 if (!padding)
66afa24f
JS
2114 return error(_("missing arguments for %s"),
2115 command_to_string(item->command));
043a4492 2116
9055e401
JS
2117 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2118 item->command == TODO_RESET) {
7dcbb3cb 2119 item->commit = NULL;
311af526
JS
2120 item->arg = bol;
2121 item->arg_len = (int)(eol - bol);
2122 return 0;
2123 }
2124
4c68e7dd
JS
2125 if (item->command == TODO_MERGE) {
2126 if (skip_prefix(bol, "-C", &bol))
2127 bol += strspn(bol, " \t");
2128 else if (skip_prefix(bol, "-c", &bol)) {
2129 bol += strspn(bol, " \t");
2130 item->flags |= TODO_EDIT_MERGE_MSG;
2131 } else {
2132 item->flags |= TODO_EDIT_MERGE_MSG;
2133 item->commit = NULL;
2134 item->arg = bol;
2135 item->arg_len = (int)(eol - bol);
2136 return 0;
2137 }
2138 }
2139
004fefa7 2140 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
043a4492
RR
2141 saved = *end_of_object_name;
2142 *end_of_object_name = '\0';
1e43ed98 2143 status = get_oid(bol, &commit_oid);
043a4492
RR
2144 *end_of_object_name = saved;
2145
c22f7dfb
JS
2146 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
2147 item->arg_len = (int)(eol - item->arg);
2148
043a4492 2149 if (status < 0)
8b637cda
JS
2150 return error(_("could not parse '%.*s'"),
2151 (int)(end_of_object_name - bol), bol);
043a4492 2152
005af339 2153 item->commit = lookup_commit_reference(r, &commit_oid);
004fefa7 2154 return !item->commit;
043a4492
RR
2155}
2156
005af339
NTND
2157static int parse_insn_buffer(struct repository *r, char *buf,
2158 struct todo_list *todo_list)
043a4492 2159{
004fefa7
JS
2160 struct todo_item *item;
2161 char *p = buf, *next_p;
6e98de72 2162 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
043a4492 2163
004fefa7 2164 for (i = 1; *p; i++, p = next_p) {
043a4492 2165 char *eol = strchrnul(p, '\n');
004fefa7
JS
2166
2167 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2168
6307041d
JS
2169 if (p != eol && eol[-1] == '\r')
2170 eol--; /* strip Carriage Return */
2171
004fefa7
JS
2172 item = append_new_todo(todo_list);
2173 item->offset_in_buf = p - todo_list->buf.buf;
005af339 2174 if (parse_insn_line(r, item, p, eol)) {
93b3df6f 2175 res = error(_("invalid line %d: %.*s"),
004fefa7 2176 i, (int)(eol - p), p);
6e98de72 2177 item->command = TODO_NOOP;
004fefa7 2178 }
6e98de72
JS
2179
2180 if (fixup_okay)
2181 ; /* do nothing */
2182 else if (is_fixup(item->command))
2183 return error(_("cannot '%s' without a previous commit"),
2184 command_to_string(item->command));
2185 else if (!is_noop(item->command))
2186 fixup_okay = 1;
043a4492 2187 }
52865279 2188
004fefa7 2189 return res;
043a4492
RR
2190}
2191
968492e4
JS
2192static int count_commands(struct todo_list *todo_list)
2193{
2194 int count = 0, i;
2195
2196 for (i = 0; i < todo_list->nr; i++)
2197 if (todo_list->items[i].command != TODO_COMMENT)
2198 count++;
2199
2200 return count;
2201}
2202
a01c2a5f
JS
2203static int get_item_line_offset(struct todo_list *todo_list, int index)
2204{
2205 return index < todo_list->nr ?
2206 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2207}
2208
2209static const char *get_item_line(struct todo_list *todo_list, int index)
2210{
2211 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2212}
2213
2214static int get_item_line_length(struct todo_list *todo_list, int index)
2215{
2216 return get_item_line_offset(todo_list, index + 1)
2217 - get_item_line_offset(todo_list, index);
2218}
2219
87805600
RS
2220static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2221{
2222 int fd;
2223 ssize_t len;
2224
2225 fd = open(path, O_RDONLY);
2226 if (fd < 0)
2227 return error_errno(_("could not open '%s'"), path);
2228 len = strbuf_read(sb, fd, 0);
2229 close(fd);
2230 if (len < 0)
2231 return error(_("could not read '%s'."), path);
2232 return len;
2233}
2234
005af339
NTND
2235static int read_populate_todo(struct repository *r,
2236 struct todo_list *todo_list,
2237 struct replay_opts *opts)
043a4492 2238{
54fd3243 2239 struct stat st;
c0246501 2240 const char *todo_file = get_todo_path(opts);
87805600 2241 int res;
043a4492 2242
004fefa7 2243 strbuf_reset(&todo_list->buf);
87805600
RS
2244 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2245 return -1;
043a4492 2246
54fd3243
SH
2247 res = stat(todo_file, &st);
2248 if (res)
2249 return error(_("could not stat '%s'"), todo_file);
2250 fill_stat_data(&todo_list->stat, &st);
2251
005af339 2252 res = parse_insn_buffer(r, todo_list->buf.buf, todo_list);
27fdbb96
JS
2253 if (res) {
2254 if (is_rebase_i(opts))
2255 return error(_("please fix this using "
2256 "'git rebase --edit-todo'."));
93b3df6f 2257 return error(_("unusable instruction sheet: '%s'"), todo_file);
27fdbb96 2258 }
2eeaf1b3 2259
52865279
JS
2260 if (!todo_list->nr &&
2261 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2262 return error(_("no commits parsed."));
2263
2eeaf1b3 2264 if (!is_rebase_i(opts)) {
004fefa7
JS
2265 enum todo_command valid =
2266 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2267 int i;
2268
2269 for (i = 0; i < todo_list->nr; i++)
2270 if (valid == todo_list->items[i].command)
2271 continue;
2272 else if (valid == TODO_PICK)
93b3df6f 2273 return error(_("cannot cherry-pick during a revert."));
004fefa7 2274 else
93b3df6f 2275 return error(_("cannot revert during a cherry-pick."));
004fefa7
JS
2276 }
2277
968492e4
JS
2278 if (is_rebase_i(opts)) {
2279 struct todo_list done = TODO_LIST_INIT;
e9d983f1 2280 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
968492e4
JS
2281
2282 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
005af339 2283 !parse_insn_buffer(r, done.buf.buf, &done))
968492e4
JS
2284 todo_list->done_nr = count_commands(&done);
2285 else
2286 todo_list->done_nr = 0;
2287
2288 todo_list->total_nr = todo_list->done_nr
2289 + count_commands(todo_list);
968492e4 2290 todo_list_release(&done);
ef80069a
JS
2291
2292 if (f) {
2293 fprintf(f, "%d\n", todo_list->total_nr);
2294 fclose(f);
2295 }
968492e4
JS
2296 }
2297
0ae42a03 2298 return 0;
043a4492
RR
2299}
2300
03a4e260
JS
2301static int git_config_string_dup(char **dest,
2302 const char *var, const char *value)
2303{
2304 if (!value)
2305 return config_error_nonbool(var);
2306 free(*dest);
2307 *dest = xstrdup(value);
2308 return 0;
2309}
2310
043a4492
RR
2311static int populate_opts_cb(const char *key, const char *value, void *data)
2312{
2313 struct replay_opts *opts = data;
2314 int error_flag = 1;
2315
2316 if (!value)
2317 error_flag = 0;
2318 else if (!strcmp(key, "options.no-commit"))
2319 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2320 else if (!strcmp(key, "options.edit"))
2321 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2322 else if (!strcmp(key, "options.signoff"))
2323 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2324 else if (!strcmp(key, "options.record-origin"))
2325 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2326 else if (!strcmp(key, "options.allow-ff"))
2327 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2328 else if (!strcmp(key, "options.mainline"))
2329 opts->mainline = git_config_int(key, value);
2330 else if (!strcmp(key, "options.strategy"))
03a4e260 2331 git_config_string_dup(&opts->strategy, key, value);
3253553e 2332 else if (!strcmp(key, "options.gpg-sign"))
03a4e260 2333 git_config_string_dup(&opts->gpg_sign, key, value);
043a4492
RR
2334 else if (!strcmp(key, "options.strategy-option")) {
2335 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2336 opts->xopts[opts->xopts_nr++] = xstrdup(value);
8d8cb4b0
PW
2337 } else if (!strcmp(key, "options.allow-rerere-auto"))
2338 opts->allow_rerere_auto =
2339 git_config_bool_or_int(key, value, &error_flag) ?
2340 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2341 else
93b3df6f 2342 return error(_("invalid key: %s"), key);
043a4492
RR
2343
2344 if (!error_flag)
93b3df6f 2345 return error(_("invalid value for %s: %s"), key, value);
043a4492
RR
2346
2347 return 0;
2348}
2349
65850686 2350void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
ca6c6b45
JS
2351{
2352 int i;
65850686 2353 char *strategy_opts_string = raw_opts;
ca6c6b45 2354
0060041d
EN
2355 if (*strategy_opts_string == ' ')
2356 strategy_opts_string++;
65850686 2357
0060041d
EN
2358 opts->xopts_nr = split_cmdline(strategy_opts_string,
2359 (const char ***)&opts->xopts);
ca6c6b45
JS
2360 for (i = 0; i < opts->xopts_nr; i++) {
2361 const char *arg = opts->xopts[i];
2362
2363 skip_prefix(arg, "--", &arg);
2364 opts->xopts[i] = xstrdup(arg);
2365 }
2366}
2367
65850686
AG
2368static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2369{
2370 strbuf_reset(buf);
2371 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2372 return;
2373 opts->strategy = strbuf_detach(buf, NULL);
2374 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2375 return;
2376
2377 parse_strategy_opts(opts, buf->buf);
2378}
2379
5adf9bdc 2380static int read_populate_opts(struct replay_opts *opts)
043a4492 2381{
a1c75762
JS
2382 if (is_rebase_i(opts)) {
2383 struct strbuf buf = STRBUF_INIT;
2384
2385 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2386 if (!starts_with(buf.buf, "-S"))
2387 strbuf_reset(&buf);
2388 else {
2389 free(opts->gpg_sign);
2390 opts->gpg_sign = xstrdup(buf.buf + 2);
2391 }
9b6d7a62
PW
2392 strbuf_reset(&buf);
2393 }
2394
2395 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2396 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2397 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2398 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2399 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2400 strbuf_reset(&buf);
a1c75762 2401 }
a1c75762 2402
556907f1
JS
2403 if (file_exists(rebase_path_verbose()))
2404 opts->verbose = 1;
2405
899b49c4
EN
2406 if (file_exists(rebase_path_quiet()))
2407 opts->quiet = 1;
2408
a852ec7f
PW
2409 if (file_exists(rebase_path_signoff())) {
2410 opts->allow_ff = 0;
2411 opts->signoff = 1;
2412 }
2413
d421afa0
JS
2414 if (file_exists(rebase_path_reschedule_failed_exec()))
2415 opts->reschedule_failed_exec = 1;
2416
ca6c6b45
JS
2417 read_strategy_opts(opts, &buf);
2418 strbuf_release(&buf);
2419
e12a7ef5
JS
2420 if (read_oneliner(&opts->current_fixups,
2421 rebase_path_current_fixups(), 1)) {
2422 const char *p = opts->current_fixups.buf;
2423 opts->current_fixup_count = 1;
2424 while ((p = strchr(p, '\n'))) {
2425 opts->current_fixup_count++;
2426 p++;
2427 }
2428 }
2429
d87d48b2
JS
2430 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2431 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2432 return error(_("unusable squash-onto"));
2433 opts->have_squash_onto = 1;
2434 }
2435
b5a67045 2436 return 0;
a1c75762 2437 }
b5a67045 2438
f932729c 2439 if (!file_exists(git_path_opts_file()))
0d00da7b
JS
2440 return 0;
2441 /*
2442 * The function git_parse_source(), called from git_config_from_file(),
2443 * may die() in case of a syntactically incorrect file. We do not care
2444 * about this case, though, because we wrote that file ourselves, so we
2445 * are pretty certain that it is syntactically correct.
2446 */
5adf9bdc 2447 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
93b3df6f 2448 return error(_("malformed options sheet: '%s'"),
0d00da7b
JS
2449 git_path_opts_file());
2450 return 0;
043a4492
RR
2451}
2452
65850686
AG
2453static void write_strategy_opts(struct replay_opts *opts)
2454{
2455 int i;
2456 struct strbuf buf = STRBUF_INIT;
2457
2458 for (i = 0; i < opts->xopts_nr; ++i)
2459 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2460
2461 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2462 strbuf_release(&buf);
2463}
2464
2465int write_basic_state(struct replay_opts *opts, const char *head_name,
2466 const char *onto, const char *orig_head)
2467{
2468 const char *quiet = getenv("GIT_QUIET");
2469
2470 if (head_name)
2471 write_file(rebase_path_head_name(), "%s\n", head_name);
2472 if (onto)
2473 write_file(rebase_path_onto(), "%s\n", onto);
2474 if (orig_head)
2475 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2476
2477 if (quiet)
2478 write_file(rebase_path_quiet(), "%s\n", quiet);
65850686 2479 if (opts->verbose)
4af51741 2480 write_file(rebase_path_verbose(), "%s", "");
65850686
AG
2481 if (opts->strategy)
2482 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2483 if (opts->xopts_nr > 0)
2484 write_strategy_opts(opts);
2485
2486 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2487 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2488 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2489 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2490
2491 if (opts->gpg_sign)
2492 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2493 if (opts->signoff)
2494 write_file(rebase_path_signoff(), "--signoff\n");
d421afa0
JS
2495 if (opts->reschedule_failed_exec)
2496 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
65850686
AG
2497
2498 return 0;
2499}
2500
004fefa7 2501static int walk_revs_populate_todo(struct todo_list *todo_list,
043a4492
RR
2502 struct replay_opts *opts)
2503{
004fefa7
JS
2504 enum todo_command command = opts->action == REPLAY_PICK ?
2505 TODO_PICK : TODO_REVERT;
414697a9 2506 const char *command_string = todo_command_info[command].str;
043a4492 2507 struct commit *commit;
043a4492 2508
34b0528b
JS
2509 if (prepare_revs(opts))
2510 return -1;
043a4492 2511
004fefa7
JS
2512 while ((commit = get_revision(opts->revs))) {
2513 struct todo_item *item = append_new_todo(todo_list);
2514 const char *commit_buffer = get_commit_buffer(commit, NULL);
2515 const char *subject;
2516 int subject_len;
2517
2518 item->command = command;
2519 item->commit = commit;
c22f7dfb
JS
2520 item->arg = NULL;
2521 item->arg_len = 0;
004fefa7
JS
2522 item->offset_in_buf = todo_list->buf.len;
2523 subject_len = find_commit_subject(commit_buffer, &subject);
2524 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2525 short_commit_name(commit), subject_len, subject);
2526 unuse_commit_buffer(commit, commit_buffer);
2527 }
8530c739
JK
2528
2529 if (!todo_list->nr)
2530 return error(_("empty commit set passed"));
2531
34b0528b 2532 return 0;
043a4492
RR
2533}
2534
2535static int create_seq_dir(void)
2536{
f932729c 2537 if (file_exists(git_path_seq_dir())) {
043a4492
RR
2538 error(_("a cherry-pick or revert is already in progress"));
2539 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2540 return -1;
a70d8f80 2541 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
93b3df6f 2542 return error_errno(_("could not create sequencer directory '%s'"),
f6e82b0d 2543 git_path_seq_dir());
043a4492
RR
2544 return 0;
2545}
2546
311fd397 2547static int save_head(const char *head)
043a4492 2548{
14bca6c6 2549 struct lock_file head_lock = LOCK_INIT;
043a4492
RR
2550 struct strbuf buf = STRBUF_INIT;
2551 int fd;
ed3f9a12 2552 ssize_t written;
043a4492 2553
311fd397 2554 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
350292a1 2555 if (fd < 0)
93b3df6f 2556 return error_errno(_("could not lock HEAD"));
043a4492 2557 strbuf_addf(&buf, "%s\n", head);
ed3f9a12
RS
2558 written = write_in_full(fd, buf.buf, buf.len);
2559 strbuf_release(&buf);
2560 if (written < 0) {
bf5c0571 2561 error_errno(_("could not write to '%s'"), git_path_head_file());
311fd397 2562 rollback_lock_file(&head_lock);
bf5c0571 2563 return -1;
311fd397 2564 }
350292a1
2565 if (commit_lock_file(&head_lock) < 0)
2566 return error(_("failed to finalize '%s'"), git_path_head_file());
311fd397 2567 return 0;
043a4492
RR
2568}
2569
1e41229d
SB
2570static int rollback_is_safe(void)
2571{
2572 struct strbuf sb = STRBUF_INIT;
2573 struct object_id expected_head, actual_head;
2574
2575 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2576 strbuf_trim(&sb);
2577 if (get_oid_hex(sb.buf, &expected_head)) {
2578 strbuf_release(&sb);
2579 die(_("could not parse %s"), git_path_abort_safety_file());
2580 }
2581 strbuf_release(&sb);
2582 }
2583 else if (errno == ENOENT)
2584 oidclr(&expected_head);
2585 else
2586 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2587
2588 if (get_oid("HEAD", &actual_head))
2589 oidclr(&actual_head);
2590
4a7e27e9 2591 return oideq(&actual_head, &expected_head);
1e41229d
SB
2592}
2593
092bbcdf 2594static int reset_for_rollback(const struct object_id *oid)
043a4492
RR
2595{
2596 const char *argv[4]; /* reset --merge <arg> + NULL */
1e41229d 2597
043a4492
RR
2598 argv[0] = "reset";
2599 argv[1] = "--merge";
092bbcdf 2600 argv[2] = oid_to_hex(oid);
043a4492
RR
2601 argv[3] = NULL;
2602 return run_command_v_opt(argv, RUN_GIT_CMD);
2603}
2604
005af339 2605static int rollback_single_pick(struct repository *r)
043a4492 2606{
092bbcdf 2607 struct object_id head_oid;
043a4492 2608
005af339
NTND
2609 if (!file_exists(git_path_cherry_pick_head(r)) &&
2610 !file_exists(git_path_revert_head(r)))
043a4492 2611 return error(_("no cherry-pick or revert in progress"));
34c290a6 2612 if (read_ref_full("HEAD", 0, &head_oid, NULL))
043a4492 2613 return error(_("cannot resolve HEAD"));
092bbcdf 2614 if (is_null_oid(&head_oid))
043a4492 2615 return error(_("cannot abort from a branch yet to be born"));
092bbcdf 2616 return reset_for_rollback(&head_oid);
043a4492
RR
2617}
2618
005af339 2619int sequencer_rollback(struct repository *r, struct replay_opts *opts)
043a4492 2620{
043a4492 2621 FILE *f;
092bbcdf 2622 struct object_id oid;
043a4492 2623 struct strbuf buf = STRBUF_INIT;
092bbcdf 2624 const char *p;
043a4492 2625
f932729c 2626 f = fopen(git_path_head_file(), "r");
043a4492
RR
2627 if (!f && errno == ENOENT) {
2628 /*
2629 * There is no multiple-cherry-pick in progress.
2630 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2631 * a single-cherry-pick in progress, abort that.
2632 */
005af339 2633 return rollback_single_pick(r);
043a4492
RR
2634 }
2635 if (!f)
f7ed1953 2636 return error_errno(_("cannot open '%s'"), git_path_head_file());
8f309aeb 2637 if (strbuf_getline_lf(&buf, f)) {
f7ed1953 2638 error(_("cannot read '%s': %s"), git_path_head_file(),
f932729c 2639 ferror(f) ? strerror(errno) : _("unexpected end of file"));
043a4492
RR
2640 fclose(f);
2641 goto fail;
2642 }
2643 fclose(f);
092bbcdf 2644 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
043a4492 2645 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
f932729c 2646 git_path_head_file());
043a4492
RR
2647 goto fail;
2648 }
092bbcdf 2649 if (is_null_oid(&oid)) {
0f974e21
MG
2650 error(_("cannot abort from a branch yet to be born"));
2651 goto fail;
2652 }
1e41229d
SB
2653
2654 if (!rollback_is_safe()) {
2655 /* Do not error, just do not rollback */
2656 warning(_("You seem to have moved HEAD. "
2657 "Not rewinding, check your HEAD!"));
2658 } else
092bbcdf 2659 if (reset_for_rollback(&oid))
043a4492 2660 goto fail;
043a4492 2661 strbuf_release(&buf);
2863584f 2662 return sequencer_remove_state(opts);
043a4492
RR
2663fail:
2664 strbuf_release(&buf);
2665 return -1;
2666}
2667
004fefa7 2668static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
043a4492 2669{
14bca6c6 2670 struct lock_file todo_lock = LOCK_INIT;
004fefa7
JS
2671 const char *todo_path = get_todo_path(opts);
2672 int next = todo_list->current, offset, fd;
043a4492 2673
84583957
JS
2674 /*
2675 * rebase -i writes "git-rebase-todo" without the currently executing
2676 * command, appending it to "done" instead.
2677 */
2678 if (is_rebase_i(opts))
2679 next++;
2680
004fefa7 2681 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
221675de 2682 if (fd < 0)
93b3df6f 2683 return error_errno(_("could not lock '%s'"), todo_path);
a01c2a5f 2684 offset = get_item_line_offset(todo_list, next);
004fefa7
JS
2685 if (write_in_full(fd, todo_list->buf.buf + offset,
2686 todo_list->buf.len - offset) < 0)
93b3df6f 2687 return error_errno(_("could not write to '%s'"), todo_path);
004fefa7 2688 if (commit_lock_file(&todo_lock) < 0)
350292a1 2689 return error(_("failed to finalize '%s'"), todo_path);
1df6df0c 2690
a01c2a5f
JS
2691 if (is_rebase_i(opts) && next > 0) {
2692 const char *done = rebase_path_done();
2693 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2694 int ret = 0;
1df6df0c 2695
a01c2a5f
JS
2696 if (fd < 0)
2697 return 0;
2698 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2699 get_item_line_length(todo_list, next - 1))
2700 < 0)
2701 ret = error_errno(_("could not write to '%s'"), done);
2702 if (close(fd) < 0)
2703 ret = error_errno(_("failed to finalize '%s'"), done);
2704 return ret;
1df6df0c 2705 }
221675de 2706 return 0;
043a4492
RR
2707}
2708
88d5a271 2709static int save_opts(struct replay_opts *opts)
043a4492 2710{
f932729c 2711 const char *opts_file = git_path_opts_file();
88d5a271 2712 int res = 0;
043a4492
RR
2713
2714 if (opts->no_commit)
88d5a271 2715 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
043a4492 2716 if (opts->edit)
88d5a271 2717 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
043a4492 2718 if (opts->signoff)
88d5a271 2719 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
043a4492 2720 if (opts->record_origin)
88d5a271 2721 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
043a4492 2722 if (opts->allow_ff)
88d5a271 2723 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
043a4492
RR
2724 if (opts->mainline) {
2725 struct strbuf buf = STRBUF_INIT;
2726 strbuf_addf(&buf, "%d", opts->mainline);
88d5a271 2727 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
043a4492
RR
2728 strbuf_release(&buf);
2729 }
2730 if (opts->strategy)
88d5a271 2731 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
3253553e 2732 if (opts->gpg_sign)
88d5a271 2733 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
043a4492
RR
2734 if (opts->xopts) {
2735 int i;
2736 for (i = 0; i < opts->xopts_nr; i++)
88d5a271 2737 res |= git_config_set_multivar_in_file_gently(opts_file,
043a4492
RR
2738 "options.strategy-option",
2739 opts->xopts[i], "^$", 0);
2740 }
8d8cb4b0
PW
2741 if (opts->allow_rerere_auto)
2742 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2743 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2744 "true" : "false");
88d5a271 2745 return res;
043a4492
RR
2746}
2747
f11c9580
NTND
2748static int make_patch(struct repository *r,
2749 struct commit *commit,
2750 struct replay_opts *opts)
56dc3ab0
JS
2751{
2752 struct strbuf buf = STRBUF_INIT;
2753 struct rev_info log_tree_opt;
2754 const char *subject, *p;
2755 int res = 0;
2756
2757 p = short_commit_name(commit);
2758 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2759 return -1;
fbd7a232
NTND
2760 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2761 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2762 res |= error(_("could not update %s"), "REBASE_HEAD");
56dc3ab0
JS
2763
2764 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2765 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 2766 repo_init_revisions(r, &log_tree_opt, NULL);
56dc3ab0
JS
2767 log_tree_opt.abbrev = 0;
2768 log_tree_opt.diff = 1;
2769 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2770 log_tree_opt.disable_stdin = 1;
2771 log_tree_opt.no_commit_id = 1;
2772 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2773 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2774 if (!log_tree_opt.diffopt.file)
2775 res |= error_errno(_("could not open '%s'"), buf.buf);
2776 else {
2777 res |= log_tree_commit(&log_tree_opt, commit);
2778 fclose(log_tree_opt.diffopt.file);
2779 }
2780 strbuf_reset(&buf);
2781
2782 strbuf_addf(&buf, "%s/message", get_dir(opts));
2783 if (!file_exists(buf.buf)) {
2784 const char *commit_buffer = get_commit_buffer(commit, NULL);
2785 find_commit_subject(commit_buffer, &subject);
2786 res |= write_message(subject, strlen(subject), buf.buf, 1);
2787 unuse_commit_buffer(commit, commit_buffer);
2788 }
2789 strbuf_release(&buf);
2790
2791 return res;
2792}
2793
2794static int intend_to_amend(void)
2795{
092bbcdf 2796 struct object_id head;
56dc3ab0
JS
2797 char *p;
2798
092bbcdf 2799 if (get_oid("HEAD", &head))
56dc3ab0
JS
2800 return error(_("cannot read HEAD"));
2801
092bbcdf 2802 p = oid_to_hex(&head);
56dc3ab0
JS
2803 return write_message(p, strlen(p), rebase_path_amend(), 1);
2804}
2805
f11c9580
NTND
2806static int error_with_patch(struct repository *r,
2807 struct commit *commit,
2808 const char *subject, int subject_len,
2809 struct replay_opts *opts,
2810 int exit_code, int to_amend)
56dc3ab0 2811{
bc9238bb 2812 if (commit) {
f11c9580 2813 if (make_patch(r, commit, opts))
bc9238bb 2814 return -1;
5a5c5e95 2815 } else if (copy_file(rebase_path_message(),
f11c9580 2816 git_path_merge_msg(r), 0666))
bc9238bb 2817 return error(_("unable to copy '%s' to '%s'"),
f11c9580 2818 git_path_merge_msg(r), rebase_path_message());
56dc3ab0
JS
2819
2820 if (to_amend) {
2821 if (intend_to_amend())
2822 return -1;
2823
02127c63
NTND
2824 fprintf(stderr,
2825 _("You can amend the commit now, with\n"
2826 "\n"
2827 " git commit --amend %s\n"
2828 "\n"
2829 "Once you are satisfied with your changes, run\n"
2830 "\n"
2831 " git rebase --continue\n"),
2832 gpg_sign_opt_quoted(opts));
bc9238bb
PW
2833 } else if (exit_code) {
2834 if (commit)
5a5c5e95
JH
2835 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
2836 short_commit_name(commit), subject_len, subject);
bc9238bb
PW
2837 else
2838 /*
2839 * We don't have the hash of the parent so
2840 * just print the line from the todo file.
2841 */
5a5c5e95
JH
2842 fprintf_ln(stderr, _("Could not merge %.*s"),
2843 subject_len, subject);
bc9238bb 2844 }
56dc3ab0
JS
2845
2846 return exit_code;
2847}
2848
f11c9580
NTND
2849static int error_failed_squash(struct repository *r,
2850 struct commit *commit,
2851 struct replay_opts *opts,
2852 int subject_len,
2853 const char *subject)
6e98de72 2854{
e12a7ef5
JS
2855 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
2856 return error(_("could not copy '%s' to '%s'"),
6e98de72 2857 rebase_path_squash_msg(), rebase_path_message());
f11c9580
NTND
2858 unlink(git_path_merge_msg(r));
2859 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
6e98de72 2860 return error(_("could not copy '%s' to '%s'"),
102de880 2861 rebase_path_message(),
f11c9580
NTND
2862 git_path_merge_msg(r));
2863 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
6e98de72
JS
2864}
2865
f11c9580 2866static int do_exec(struct repository *r, const char *command_line)
311af526 2867{
09d7b6c6 2868 struct argv_array child_env = ARGV_ARRAY_INIT;
311af526
JS
2869 const char *child_argv[] = { NULL, NULL };
2870 int dirty, status;
2871
2872 fprintf(stderr, "Executing: %s\n", command_line);
2873 child_argv[0] = command_line;
09d7b6c6 2874 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
ab5e67d7 2875 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
2876 absolute_path(get_git_work_tree()));
09d7b6c6
JK
2877 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2878 child_env.argv);
311af526
JS
2879
2880 /* force re-reading of the cache */
e1ff0a32 2881 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
311af526
JS
2882 return error(_("could not read index"));
2883
f11c9580 2884 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
311af526
JS
2885
2886 if (status) {
2887 warning(_("execution failed: %s\n%s"
2888 "You can fix the problem, and then run\n"
2889 "\n"
2890 " git rebase --continue\n"
2891 "\n"),
2892 command_line,
2893 dirty ? N_("and made changes to the index and/or the "
2894 "working tree\n") : "");
2895 if (status == 127)
2896 /* command not found */
2897 status = 1;
2898 } else if (dirty) {
2899 warning(_("execution succeeded: %s\nbut "
2900 "left changes to the index and/or the working tree\n"
2901 "Commit or stash your changes, and then run\n"
2902 "\n"
2903 " git rebase --continue\n"
2904 "\n"), command_line);
2905 status = 1;
2906 }
2907
09d7b6c6
JK
2908 argv_array_clear(&child_env);
2909
311af526
JS
2910 return status;
2911}
2912
9055e401
JS
2913static int safe_append(const char *filename, const char *fmt, ...)
2914{
2915 va_list ap;
2916 struct lock_file lock = LOCK_INIT;
2917 int fd = hold_lock_file_for_update(&lock, filename,
2918 LOCK_REPORT_ON_ERROR);
2919 struct strbuf buf = STRBUF_INIT;
2920
2921 if (fd < 0)
2922 return -1;
2923
2924 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2925 error_errno(_("could not read '%s'"), filename);
2926 rollback_lock_file(&lock);
2927 return -1;
2928 }
2929 strbuf_complete(&buf, '\n');
2930 va_start(ap, fmt);
2931 strbuf_vaddf(&buf, fmt, ap);
2932 va_end(ap);
2933
2934 if (write_in_full(fd, buf.buf, buf.len) < 0) {
2935 error_errno(_("could not write to '%s'"), filename);
2936 strbuf_release(&buf);
2937 rollback_lock_file(&lock);
2938 return -1;
2939 }
2940 if (commit_lock_file(&lock) < 0) {
2941 strbuf_release(&buf);
2942 rollback_lock_file(&lock);
2943 return error(_("failed to finalize '%s'"), filename);
2944 }
2945
2946 strbuf_release(&buf);
2947 return 0;
2948}
2949
f11c9580 2950static int do_label(struct repository *r, const char *name, int len)
9055e401 2951{
f11c9580 2952 struct ref_store *refs = get_main_ref_store(r);
9055e401
JS
2953 struct ref_transaction *transaction;
2954 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
2955 struct strbuf msg = STRBUF_INIT;
2956 int ret = 0;
2957 struct object_id head_oid;
2958
2959 if (len == 1 && *name == '#')
02127c63 2960 return error(_("illegal label name: '%.*s'"), len, name);
9055e401
JS
2961
2962 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2963 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
2964
2965 transaction = ref_store_transaction_begin(refs, &err);
2966 if (!transaction) {
2967 error("%s", err.buf);
2968 ret = -1;
2969 } else if (get_oid("HEAD", &head_oid)) {
2970 error(_("could not read HEAD"));
2971 ret = -1;
2972 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
2973 NULL, 0, msg.buf, &err) < 0 ||
2974 ref_transaction_commit(transaction, &err)) {
2975 error("%s", err.buf);
2976 ret = -1;
2977 }
2978 ref_transaction_free(transaction);
2979 strbuf_release(&err);
2980 strbuf_release(&msg);
2981
2982 if (!ret)
2983 ret = safe_append(rebase_path_refs_to_delete(),
2984 "%s\n", ref_name.buf);
2985 strbuf_release(&ref_name);
2986
2987 return ret;
2988}
2989
2990static const char *reflog_message(struct replay_opts *opts,
2991 const char *sub_action, const char *fmt, ...);
2992
f11c9580
NTND
2993static int do_reset(struct repository *r,
2994 const char *name, int len,
2995 struct replay_opts *opts)
9055e401
JS
2996{
2997 struct strbuf ref_name = STRBUF_INIT;
2998 struct object_id oid;
2999 struct lock_file lock = LOCK_INIT;
3000 struct tree_desc desc;
3001 struct tree *tree;
3002 struct unpack_trees_options unpack_tree_opts;
71571cd7 3003 int ret = 0;
9055e401 3004
3a95f31d 3005 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
9055e401
JS
3006 return -1;
3007
ebddf393
JS
3008 if (len == 10 && !strncmp("[new root]", name, len)) {
3009 if (!opts->have_squash_onto) {
3010 const char *hex;
3011 if (commit_tree("", 0, the_hash_algo->empty_tree,
3012 NULL, &opts->squash_onto,
3013 NULL, NULL))
3014 return error(_("writing fake root commit"));
3015 opts->have_squash_onto = 1;
3016 hex = oid_to_hex(&opts->squash_onto);
3017 if (write_message(hex, strlen(hex),
3018 rebase_path_squash_onto(), 0))
3019 return error(_("writing squash-onto"));
3020 }
3021 oidcpy(&oid, &opts->squash_onto);
3022 } else {
71571cd7
3023 int i;
3024
ebddf393
JS
3025 /* Determine the length of the label */
3026 for (i = 0; i < len; i++)
3027 if (isspace(name[i]))
71571cd7
3028 break;
3029 len = i;
ebddf393
JS
3030
3031 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3032 if (get_oid(ref_name.buf, &oid) &&
3033 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3034 error(_("could not read '%s'"), ref_name.buf);
3035 rollback_lock_file(&lock);
3036 strbuf_release(&ref_name);
3037 return -1;
3038 }
9055e401
JS
3039 }
3040
3041 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3042 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3043 unpack_tree_opts.head_idx = 1;
f11c9580
NTND
3044 unpack_tree_opts.src_index = r->index;
3045 unpack_tree_opts.dst_index = r->index;
9055e401
JS
3046 unpack_tree_opts.fn = oneway_merge;
3047 unpack_tree_opts.merge = 1;
3048 unpack_tree_opts.update = 1;
3049
e1ff0a32 3050 if (repo_read_index_unmerged(r)) {
9055e401
JS
3051 rollback_lock_file(&lock);
3052 strbuf_release(&ref_name);
3053 return error_resolve_conflict(_(action_name(opts)));
3054 }
3055
3056 if (!fill_tree_descriptor(&desc, &oid)) {
3057 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3058 rollback_lock_file(&lock);
3059 free((void *)desc.buffer);
3060 strbuf_release(&ref_name);
3061 return -1;
3062 }
3063
3064 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3065 rollback_lock_file(&lock);
3066 free((void *)desc.buffer);
3067 strbuf_release(&ref_name);
3068 return -1;
3069 }
3070
3071 tree = parse_tree_indirect(&oid);
c207e9e1 3072 prime_cache_tree(r, r->index, tree);
9055e401 3073
f11c9580 3074 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
9055e401
JS
3075 ret = error(_("could not write index"));
3076 free((void *)desc.buffer);
3077
3078 if (!ret)
3079 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3080 len, name), "HEAD", &oid,
3081 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3082
3083 strbuf_release(&ref_name);
3084 return ret;
3085}
3086
2b6ad0f4
JS
3087static struct commit *lookup_label(const char *label, int len,
3088 struct strbuf *buf)
3089{
3090 struct commit *commit;
3091
3092 strbuf_reset(buf);
3093 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3094 commit = lookup_commit_reference_by_name(buf->buf);
3095 if (!commit) {
3096 /* fall back to non-rewritten ref or commit */
3097 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3098 commit = lookup_commit_reference_by_name(buf->buf);
3099 }
3100
3101 if (!commit)
3102 error(_("could not resolve '%s'"), buf->buf);
3103
3104 return commit;
3105}
3106
f11c9580
NTND
3107static int do_merge(struct repository *r,
3108 struct commit *commit,
3109 const char *arg, int arg_len,
4c68e7dd
JS
3110 int flags, struct replay_opts *opts)
3111{
3112 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3113 EDIT_MSG | VERIFY_MSG : 0;
3114 struct strbuf ref_name = STRBUF_INIT;
3115 struct commit *head_commit, *merge_commit, *i;
3116 struct commit_list *bases, *j, *reversed = NULL;
2b6ad0f4 3117 struct commit_list *to_merge = NULL, **tail = &to_merge;
4c68e7dd 3118 struct merge_options o;
2b6ad0f4 3119 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4c68e7dd
JS
3120 static struct lock_file lock;
3121 const char *p;
3122
3a95f31d 3123 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4c68e7dd
JS
3124 ret = -1;
3125 goto leave_merge;
3126 }
3127
3128 head_commit = lookup_commit_reference_by_name("HEAD");
3129 if (!head_commit) {
3130 ret = error(_("cannot merge without a current revision"));
3131 goto leave_merge;
3132 }
3133
2b6ad0f4
JS
3134 /*
3135 * For octopus merges, the arg starts with the list of revisions to be
3136 * merged. The list is optionally followed by '#' and the oneline.
3137 */
3138 merge_arg_len = oneline_offset = arg_len;
3139 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3140 if (!*p)
3141 break;
3142 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3143 p += 1 + strspn(p + 1, " \t\n");
3144 oneline_offset = p - arg;
3145 break;
3146 }
3147 k = strcspn(p, " \t\n");
3148 if (!k)
3149 continue;
3150 merge_commit = lookup_label(p, k, &ref_name);
3151 if (!merge_commit) {
3152 ret = error(_("unable to parse '%.*s'"), k, p);
3153 goto leave_merge;
3154 }
3155 tail = &commit_list_insert(merge_commit, tail)->next;
3156 p += k;
3157 merge_arg_len = p - arg;
4c68e7dd
JS
3158 }
3159
2b6ad0f4
JS
3160 if (!to_merge) {
3161 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4c68e7dd
JS
3162 goto leave_merge;
3163 }
3164
9c85a1c2 3165 if (opts->have_squash_onto &&
4a7e27e9 3166 oideq(&head_commit->object.oid, &opts->squash_onto)) {
9c85a1c2
JS
3167 /*
3168 * When the user tells us to "merge" something into a
3169 * "[new root]", let's simply fast-forward to the merge head.
3170 */
3171 rollback_lock_file(&lock);
2b6ad0f4
JS
3172 if (to_merge->next)
3173 ret = error(_("octopus merge cannot be executed on "
3174 "top of a [new root]"));
3175 else
f11c9580 3176 ret = fast_forward_to(r, &to_merge->item->object.oid,
2b6ad0f4
JS
3177 &head_commit->object.oid, 0,
3178 opts);
9c85a1c2
JS
3179 goto leave_merge;
3180 }
3181
4c68e7dd
JS
3182 if (commit) {
3183 const char *message = get_commit_buffer(commit, NULL);
3184 const char *body;
3185 int len;
3186
3187 if (!message) {
3188 ret = error(_("could not get commit message of '%s'"),
3189 oid_to_hex(&commit->object.oid));
3190 goto leave_merge;
3191 }
3192 write_author_script(message);
3193 find_commit_subject(message, &body);
3194 len = strlen(body);
f11c9580 3195 ret = write_message(body, len, git_path_merge_msg(r), 0);
4c68e7dd
JS
3196 unuse_commit_buffer(commit, message);
3197 if (ret) {
3198 error_errno(_("could not write '%s'"),
f11c9580 3199 git_path_merge_msg(r));
4c68e7dd
JS
3200 goto leave_merge;
3201 }
3202 } else {
3203 struct strbuf buf = STRBUF_INIT;
3204 int len;
3205
3206 strbuf_addf(&buf, "author %s", git_author_info(0));
3207 write_author_script(buf.buf);
3208 strbuf_reset(&buf);
3209
3210 if (oneline_offset < arg_len) {
3211 p = arg + oneline_offset;
3212 len = arg_len - oneline_offset;
3213 } else {
2b6ad0f4
JS
3214 strbuf_addf(&buf, "Merge %s '%.*s'",
3215 to_merge->next ? "branches" : "branch",
4c68e7dd
JS
3216 merge_arg_len, arg);
3217 p = buf.buf;
3218 len = buf.len;
3219 }
3220
f11c9580 3221 ret = write_message(p, len, git_path_merge_msg(r), 0);
4c68e7dd
JS
3222 strbuf_release(&buf);
3223 if (ret) {
3224 error_errno(_("could not write '%s'"),
f11c9580 3225 git_path_merge_msg(r));
4c68e7dd
JS
3226 goto leave_merge;
3227 }
3228 }
3229
d1e8b011
JS
3230 /*
3231 * If HEAD is not identical to the first parent of the original merge
3232 * commit, we cannot fast-forward.
3233 */
3234 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4a7e27e9
JK
3235 oideq(&commit->parents->item->object.oid,
3236 &head_commit->object.oid);
d1e8b011
JS
3237
3238 /*
2b6ad0f4 3239 * If any merge head is different from the original one, we cannot
d1e8b011
JS
3240 * fast-forward.
3241 */
3242 if (can_fast_forward) {
2b6ad0f4 3243 struct commit_list *p = commit->parents->next;
d1e8b011 3244
2b6ad0f4 3245 for (j = to_merge; j && p; j = j->next, p = p->next)
9001dc2a 3246 if (!oideq(&j->item->object.oid,
2b6ad0f4
JS
3247 &p->item->object.oid)) {
3248 can_fast_forward = 0;
3249 break;
3250 }
3251 /*
3252 * If the number of merge heads differs from the original merge
3253 * commit, we cannot fast-forward.
3254 */
3255 if (j || p)
d1e8b011
JS
3256 can_fast_forward = 0;
3257 }
3258
2b6ad0f4 3259 if (can_fast_forward) {
d1e8b011 3260 rollback_lock_file(&lock);
f11c9580 3261 ret = fast_forward_to(r, &commit->object.oid,
d1e8b011
JS
3262 &head_commit->object.oid, 0, opts);
3263 goto leave_merge;
3264 }
3265
2b6ad0f4
JS
3266 if (to_merge->next) {
3267 /* Octopus merge */
3268 struct child_process cmd = CHILD_PROCESS_INIT;
3269
3270 if (read_env_script(&cmd.env_array)) {
3271 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3272
3273 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3274 goto leave_merge;
3275 }
3276
3277 cmd.git_cmd = 1;
3278 argv_array_push(&cmd.args, "merge");
3279 argv_array_push(&cmd.args, "-s");
3280 argv_array_push(&cmd.args, "octopus");
3281 argv_array_push(&cmd.args, "--no-edit");
3282 argv_array_push(&cmd.args, "--no-ff");
3283 argv_array_push(&cmd.args, "--no-log");
3284 argv_array_push(&cmd.args, "--no-stat");
3285 argv_array_push(&cmd.args, "-F");
f11c9580 3286 argv_array_push(&cmd.args, git_path_merge_msg(r));
2b6ad0f4
JS
3287 if (opts->gpg_sign)
3288 argv_array_push(&cmd.args, opts->gpg_sign);
3289
3290 /* Add the tips to be merged */
3291 for (j = to_merge; j; j = j->next)
3292 argv_array_push(&cmd.args,
3293 oid_to_hex(&j->item->object.oid));
3294
3295 strbuf_release(&ref_name);
f11c9580 3296 unlink(git_path_cherry_pick_head(r));
2b6ad0f4
JS
3297 rollback_lock_file(&lock);
3298
3299 rollback_lock_file(&lock);
3300 ret = run_command(&cmd);
3301
3302 /* force re-reading of the cache */
f11c9580 3303 if (!ret && (discard_index(r->index) < 0 ||
e1ff0a32 3304 repo_read_index(r) < 0))
2b6ad0f4
JS
3305 ret = error(_("could not read index"));
3306 goto leave_merge;
3307 }
3308
3309 merge_commit = to_merge->item;
4c68e7dd 3310 bases = get_merge_bases(head_commit, merge_commit);
4a7e27e9
JK
3311 if (bases && oideq(&merge_commit->object.oid,
3312 &bases->item->object.oid)) {
7ccdf65b
JS
3313 ret = 0;
3314 /* skip merging an ancestor of HEAD */
3315 goto leave_merge;
3316 }
3317
85f8d9da 3318 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
cde55548
JH
3319 git_path_merge_head(r), 0);
3320 write_message("no-ff", 5, git_path_merge_mode(r), 0);
85f8d9da 3321
4c68e7dd
JS
3322 for (j = bases; j; j = j->next)
3323 commit_list_insert(j->item, &reversed);
3324 free_commit_list(bases);
3325
e1ff0a32 3326 repo_read_index(r);
0d6caa2d 3327 init_merge_options(&o, r);
4c68e7dd
JS
3328 o.branch1 = "HEAD";
3329 o.branch2 = ref_name.buf;
3330 o.buffer_output = 2;
3331
3332 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3333 if (ret <= 0)
3334 fputs(o.obuf.buf, stdout);
3335 strbuf_release(&o.obuf);
3336 if (ret < 0) {
3337 error(_("could not even attempt to merge '%.*s'"),
3338 merge_arg_len, arg);
3339 goto leave_merge;
3340 }
3341 /*
3342 * The return value of merge_recursive() is 1 on clean, and 0 on
3343 * unclean merge.
3344 *
3345 * Let's reverse that, so that do_merge() returns 0 upon success and
3346 * 1 upon failed merge (keeping the return value -1 for the cases where
3347 * we will want to reschedule the `merge` command).
3348 */
3349 ret = !ret;
3350
f11c9580
NTND
3351 if (r->index->cache_changed &&
3352 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4c68e7dd
JS
3353 ret = error(_("merge: Unable to write new index file"));
3354 goto leave_merge;
3355 }
3356
3357 rollback_lock_file(&lock);
3358 if (ret)
f11c9580 3359 repo_rerere(r, opts->allow_rerere_auto);
4c68e7dd
JS
3360 else
3361 /*
3362 * In case of problems, we now want to return a positive
3363 * value (a negative one would indicate that the `merge`
3364 * command needs to be rescheduled).
3365 */
f11c9580
NTND
3366 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3367 run_commit_flags);
4c68e7dd
JS
3368
3369leave_merge:
3370 strbuf_release(&ref_name);
3371 rollback_lock_file(&lock);
2b6ad0f4 3372 free_commit_list(to_merge);
4c68e7dd
JS
3373 return ret;
3374}
3375
6e98de72
JS
3376static int is_final_fixup(struct todo_list *todo_list)
3377{
3378 int i = todo_list->current;
3379
3380 if (!is_fixup(todo_list->items[i].command))
3381 return 0;
3382
3383 while (++i < todo_list->nr)
3384 if (is_fixup(todo_list->items[i].command))
3385 return 0;
3386 else if (!is_noop(todo_list->items[i].command))
3387 break;
3388 return 1;
3389}
3390
25cb8df9
JS
3391static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3392{
3393 int i;
3394
3395 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3396 if (!is_noop(todo_list->items[i].command))
3397 return todo_list->items[i].command;
3398
3399 return -1;
3400}
3401
796c7972
JS
3402static int apply_autostash(struct replay_opts *opts)
3403{
3404 struct strbuf stash_sha1 = STRBUF_INIT;
3405 struct child_process child = CHILD_PROCESS_INIT;
3406 int ret = 0;
3407
3408 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3409 strbuf_release(&stash_sha1);
3410 return 0;
3411 }
3412 strbuf_trim(&stash_sha1);
3413
3414 child.git_cmd = 1;
79a62269
PW
3415 child.no_stdout = 1;
3416 child.no_stderr = 1;
796c7972
JS
3417 argv_array_push(&child.args, "stash");
3418 argv_array_push(&child.args, "apply");
3419 argv_array_push(&child.args, stash_sha1.buf);
3420 if (!run_command(&child))
cdb866b3 3421 fprintf(stderr, _("Applied autostash.\n"));
796c7972
JS
3422 else {
3423 struct child_process store = CHILD_PROCESS_INIT;
3424
3425 store.git_cmd = 1;
3426 argv_array_push(&store.args, "stash");
3427 argv_array_push(&store.args, "store");
3428 argv_array_push(&store.args, "-m");
3429 argv_array_push(&store.args, "autostash");
3430 argv_array_push(&store.args, "-q");
3431 argv_array_push(&store.args, stash_sha1.buf);
3432 if (run_command(&store))
3433 ret = error(_("cannot store %s"), stash_sha1.buf);
3434 else
cdb866b3
JS
3435 fprintf(stderr,
3436 _("Applying autostash resulted in conflicts.\n"
3437 "Your changes are safe in the stash.\n"
3438 "You can run \"git stash pop\" or"
3439 " \"git stash drop\" at any time.\n"));
796c7972
JS
3440 }
3441
3442 strbuf_release(&stash_sha1);
3443 return ret;
3444}
3445
96e832a5
JS
3446static const char *reflog_message(struct replay_opts *opts,
3447 const char *sub_action, const char *fmt, ...)
3448{
3449 va_list ap;
3450 static struct strbuf buf = STRBUF_INIT;
3451
3452 va_start(ap, fmt);
3453 strbuf_reset(&buf);
3454 strbuf_addstr(&buf, action_name(opts));
3455 if (sub_action)
3456 strbuf_addf(&buf, " (%s)", sub_action);
3457 if (fmt) {
3458 strbuf_addstr(&buf, ": ");
3459 strbuf_vaddf(&buf, fmt, ap);
3460 }
3461 va_end(ap);
3462
3463 return buf.buf;
3464}
3465
2c58483a
AG
3466static int run_git_checkout(struct replay_opts *opts, const char *commit,
3467 const char *action)
3468{
3469 struct child_process cmd = CHILD_PROCESS_INIT;
3470
3471 cmd.git_cmd = 1;
3472
3473 argv_array_push(&cmd.args, "checkout");
3474 argv_array_push(&cmd.args, commit);
3475 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3476
3477 if (opts->verbose)
3478 return run_command(&cmd);
3479 else
3480 return run_command_silent_on_success(&cmd);
3481}
3482
3483int prepare_branch_to_be_rebased(struct replay_opts *opts, const char *commit)
3484{
3485 const char *action;
3486
3487 if (commit && *commit) {
3488 action = reflog_message(opts, "start", "checkout %s", commit);
3489 if (run_git_checkout(opts, commit, action))
3490 return error(_("could not checkout %s"), commit);
3491 }
3492
3493 return 0;
3494}
3495
91f0d95d
AG
3496static int checkout_onto(struct replay_opts *opts,
3497 const char *onto_name, const char *onto,
3498 const char *orig_head)
4df66c40
AG
3499{
3500 struct object_id oid;
3501 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3502
3503 if (get_oid(orig_head, &oid))
3504 return error(_("%s: not a valid OID"), orig_head);
3505
3506 if (run_git_checkout(opts, onto, action)) {
3507 apply_autostash(opts);
3508 sequencer_remove_state(opts);
3509 return error(_("could not detach HEAD"));
3510 }
3511
3512 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3513}
3514
005af339 3515static int stopped_at_head(struct repository *r)
71f82465
JS
3516{
3517 struct object_id head;
3518 struct commit *commit;
3519 struct commit_message message;
3520
789b1f70 3521 if (get_oid("HEAD", &head) ||
005af339 3522 !(commit = lookup_commit(r, &head)) ||
71f82465
JS
3523 parse_commit(commit) || get_message(commit, &message))
3524 fprintf(stderr, _("Stopped at HEAD\n"));
3525 else {
3526 fprintf(stderr, _("Stopped at %s\n"), message.label);
3527 free_message(commit, &message);
3528 }
3529 return 0;
3530
3531}
3532
cb5206ea
JS
3533static const char rescheduled_advice[] =
3534N_("Could not execute the todo command\n"
3535"\n"
3536" %.*s"
3537"\n"
3538"It has been rescheduled; To edit the command before continuing, please\n"
3539"edit the todo list first:\n"
3540"\n"
3541" git rebase --edit-todo\n"
3542" git rebase --continue\n");
3543
f11c9580
NTND
3544static int pick_commits(struct repository *r,
3545 struct todo_list *todo_list,
3546 struct replay_opts *opts)
043a4492 3547{
9055e401 3548 int res = 0, reschedule = 0;
043a4492
RR
3549
3550 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3551 if (opts->allow_ff)
3552 assert(!(opts->signoff || opts->no_commit ||
3553 opts->record_origin || opts->edit));
f11c9580 3554 if (read_and_refresh_cache(r, opts))
0d9c6dc9 3555 return -1;
043a4492 3556
004fefa7
JS
3557 while (todo_list->current < todo_list->nr) {
3558 struct todo_item *item = todo_list->items + todo_list->current;
3559 if (save_todo(todo_list, opts))
221675de 3560 return -1;
6e98de72 3561 if (is_rebase_i(opts)) {
ef80069a
JS
3562 if (item->command != TODO_COMMENT) {
3563 FILE *f = fopen(rebase_path_msgnum(), "w");
3564
3565 todo_list->done_nr++;
3566
3567 if (f) {
3568 fprintf(f, "%d\n", todo_list->done_nr);
3569 fclose(f);
3570 }
899b49c4
EN
3571 if (!opts->quiet)
3572 fprintf(stderr, "Rebasing (%d/%d)%s",
3573 todo_list->done_nr,
3574 todo_list->total_nr,
3575 opts->verbose ? "\n" : "\r");
ef80069a 3576 }
6e98de72
JS
3577 unlink(rebase_path_message());
3578 unlink(rebase_path_author_script());
3579 unlink(rebase_path_stopped_sha());
3580 unlink(rebase_path_amend());
69c92209 3581 unlink(git_path_merge_head(the_repository));
fbd7a232 3582 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
71f82465
JS
3583
3584 if (item->command == TODO_BREAK)
005af339 3585 return stopped_at_head(r);
6e98de72
JS
3586 }
3587 if (item->command <= TODO_SQUASH) {
8ab37ef2
JS
3588 if (is_rebase_i(opts))
3589 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3590 command_to_string(item->command), NULL),
3591 1);
f11c9580 3592 res = do_pick_commit(r, item->command, item->commit,
6e98de72 3593 opts, is_final_fixup(todo_list));
9d7bf3cf
JS
3594 if (is_rebase_i(opts) && res < 0) {
3595 /* Reschedule */
cb5206ea
JS
3596 advise(_(rescheduled_advice),
3597 get_item_line_length(todo_list,
3598 todo_list->current),
3599 get_item_line(todo_list,
3600 todo_list->current));
9d7bf3cf
JS
3601 todo_list->current--;
3602 if (save_todo(todo_list, opts))
3603 return -1;
3604 }
56dc3ab0
JS
3605 if (item->command == TODO_EDIT) {
3606 struct commit *commit = item->commit;
3607 if (!res)
99429213 3608 fprintf(stderr,
a42e1b41 3609 _("Stopped at %s... %.*s\n"),
56dc3ab0
JS
3610 short_commit_name(commit),
3611 item->arg_len, item->arg);
f11c9580 3612 return error_with_patch(r, commit,
56dc3ab0
JS
3613 item->arg, item->arg_len, opts, res,
3614 !res);
3615 }
25cb8df9
JS
3616 if (is_rebase_i(opts) && !res)
3617 record_in_rewritten(&item->commit->object.oid,
3618 peek_command(todo_list, 1));
6e98de72
JS
3619 if (res && is_fixup(item->command)) {
3620 if (res == 1)
3621 intend_to_amend();
f11c9580 3622 return error_failed_squash(r, item->commit, opts,
6e98de72 3623 item->arg_len, item->arg);
a9279c67
PW
3624 } else if (res && is_rebase_i(opts) && item->commit) {
3625 int to_amend = 0;
3626 struct object_id oid;
3627
3628 /*
3629 * If we are rewording and have either
3630 * fast-forwarded already, or are about to
3631 * create a new root commit, we want to amend,
3632 * otherwise we do not.
3633 */
3634 if (item->command == TODO_REWORD &&
3635 !get_oid("HEAD", &oid) &&
4a7e27e9 3636 (oideq(&item->commit->object.oid, &oid) ||
a9279c67 3637 (opts->have_squash_onto &&
4a7e27e9 3638 oideq(&opts->squash_onto, &oid))))
a9279c67
PW
3639 to_amend = 1;
3640
f11c9580 3641 return res | error_with_patch(r, item->commit,
a9279c67
PW
3642 item->arg, item->arg_len, opts,
3643 res, to_amend);
3644 }
311af526
JS
3645 } else if (item->command == TODO_EXEC) {
3646 char *end_of_arg = (char *)(item->arg + item->arg_len);
3647 int saved = *end_of_arg;
54fd3243 3648 struct stat st;
311af526
JS
3649
3650 *end_of_arg = '\0';
f11c9580 3651 res = do_exec(r, item->arg);
311af526 3652 *end_of_arg = saved;
54fd3243 3653
d421afa0
JS
3654 if (res) {
3655 if (opts->reschedule_failed_exec)
3656 reschedule = 1;
3657 } else if (stat(get_todo_path(opts), &st))
54fd3243
SH
3658 res = error_errno(_("could not stat '%s'"),
3659 get_todo_path(opts));
3660 else if (match_stat_data(&todo_list->stat, &st)) {
01710d0a 3661 /* Reread the todo file if it has changed. */
54fd3243 3662 todo_list_release(todo_list);
005af339 3663 if (read_populate_todo(r, todo_list, opts))
54fd3243
SH
3664 res = -1; /* message was printed */
3665 /* `current` will be incremented below */
3666 todo_list->current = -1;
3667 }
9055e401 3668 } else if (item->command == TODO_LABEL) {
f11c9580 3669 if ((res = do_label(r, item->arg, item->arg_len)))
9055e401
JS
3670 reschedule = 1;
3671 } else if (item->command == TODO_RESET) {
f11c9580 3672 if ((res = do_reset(r, item->arg, item->arg_len, opts)))
9055e401 3673 reschedule = 1;
4c68e7dd 3674 } else if (item->command == TODO_MERGE) {
f11c9580 3675 if ((res = do_merge(r, item->commit,
4c68e7dd
JS
3676 item->arg, item->arg_len,
3677 item->flags, opts)) < 0)
3678 reschedule = 1;
537e7d61
JS
3679 else if (item->commit)
3680 record_in_rewritten(&item->commit->object.oid,
3681 peek_command(todo_list, 1));
3682 if (res > 0)
4c68e7dd 3683 /* failed with merge conflicts */
f11c9580 3684 return error_with_patch(r, item->commit,
4c68e7dd
JS
3685 item->arg,
3686 item->arg_len, opts,
3687 res, 0);
56dc3ab0 3688 } else if (!is_noop(item->command))
25c43667
JS
3689 return error(_("unknown command %d"), item->command);
3690
9055e401
JS
3691 if (reschedule) {
3692 advise(_(rescheduled_advice),
3693 get_item_line_length(todo_list,
3694 todo_list->current),
3695 get_item_line(todo_list, todo_list->current));
3696 todo_list->current--;
3697 if (save_todo(todo_list, opts))
3698 return -1;
4c68e7dd 3699 if (item->commit)
f11c9580
NTND
3700 return error_with_patch(r,
3701 item->commit,
4c68e7dd
JS
3702 item->arg,
3703 item->arg_len, opts,
3704 res, 0);
9055e401
JS
3705 }
3706
004fefa7 3707 todo_list->current++;
043a4492
RR
3708 if (res)
3709 return res;
3710 }
3711
56dc3ab0 3712 if (is_rebase_i(opts)) {
4b83ce9f 3713 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
25cb8df9 3714 struct stat st;
556907f1 3715
56dc3ab0
JS
3716 /* Stopped in the middle, as planned? */
3717 if (todo_list->current < todo_list->nr)
3718 return 0;
556907f1 3719
4b83ce9f
JS
3720 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3721 starts_with(head_ref.buf, "refs/")) {
96e832a5 3722 const char *msg;
092bbcdf 3723 struct object_id head, orig;
4b83ce9f
JS
3724 int res;
3725
092bbcdf 3726 if (get_oid("HEAD", &head)) {
4b83ce9f
JS
3727 res = error(_("cannot read HEAD"));
3728cleanup_head_ref:
3729 strbuf_release(&head_ref);
3730 strbuf_release(&buf);
3731 return res;
3732 }
3733 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
092bbcdf 3734 get_oid_hex(buf.buf, &orig)) {
4b83ce9f
JS
3735 res = error(_("could not read orig-head"));
3736 goto cleanup_head_ref;
3737 }
4ab867b8 3738 strbuf_reset(&buf);
4b83ce9f
JS
3739 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3740 res = error(_("could not read 'onto'"));
3741 goto cleanup_head_ref;
3742 }
96e832a5
JS
3743 msg = reflog_message(opts, "finish", "%s onto %s",
3744 head_ref.buf, buf.buf);
ae077771 3745 if (update_ref(msg, head_ref.buf, &head, &orig,
91774afc 3746 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4b83ce9f
JS
3747 res = error(_("could not update %s"),
3748 head_ref.buf);
3749 goto cleanup_head_ref;
3750 }
96e832a5 3751 msg = reflog_message(opts, "finish", "returning to %s",
4b83ce9f 3752 head_ref.buf);
96e832a5 3753 if (create_symref("HEAD", head_ref.buf, msg)) {
4b83ce9f
JS
3754 res = error(_("could not update HEAD to %s"),
3755 head_ref.buf);
3756 goto cleanup_head_ref;
3757 }
3758 strbuf_reset(&buf);
3759 }
3760
556907f1
JS
3761 if (opts->verbose) {
3762 struct rev_info log_tree_opt;
3763 struct object_id orig, head;
3764
3765 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 3766 repo_init_revisions(r, &log_tree_opt, NULL);
556907f1
JS
3767 log_tree_opt.diff = 1;
3768 log_tree_opt.diffopt.output_format =
3769 DIFF_FORMAT_DIFFSTAT;
3770 log_tree_opt.disable_stdin = 1;
3771
3772 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
e82caf38 3773 !get_oid(buf.buf, &orig) &&
3774 !get_oid("HEAD", &head)) {
66f414f8
BW
3775 diff_tree_oid(&orig, &head, "",
3776 &log_tree_opt.diffopt);
556907f1
JS
3777 log_tree_diff_flush(&log_tree_opt);
3778 }
3779 }
25cb8df9
JS
3780 flush_rewritten_pending();
3781 if (!stat(rebase_path_rewritten_list(), &st) &&
3782 st.st_size > 0) {
3783 struct child_process child = CHILD_PROCESS_INIT;
79516045
JS
3784 const char *post_rewrite_hook =
3785 find_hook("post-rewrite");
25cb8df9
JS
3786
3787 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3788 child.git_cmd = 1;
3789 argv_array_push(&child.args, "notes");
3790 argv_array_push(&child.args, "copy");
3791 argv_array_push(&child.args, "--for-rewrite=rebase");
3792 /* we don't care if this copying failed */
3793 run_command(&child);
79516045
JS
3794
3795 if (post_rewrite_hook) {
3796 struct child_process hook = CHILD_PROCESS_INIT;
3797
3798 hook.in = open(rebase_path_rewritten_list(),
3799 O_RDONLY);
3800 hook.stdout_to_stderr = 1;
6206286e 3801 hook.trace2_hook_name = "post-rewrite";
79516045
JS
3802 argv_array_push(&hook.args, post_rewrite_hook);
3803 argv_array_push(&hook.args, "rebase");
3804 /* we don't care if this hook failed */
3805 run_command(&hook);
3806 }
25cb8df9 3807 }
796c7972 3808 apply_autostash(opts);
25cb8df9 3809
899b49c4
EN
3810 if (!opts->quiet)
3811 fprintf(stderr,
3812 "Successfully rebased and updated %s.\n",
3813 head_ref.buf);
5da4966f 3814
556907f1 3815 strbuf_release(&buf);
4b83ce9f 3816 strbuf_release(&head_ref);
56dc3ab0
JS
3817 }
3818
043a4492
RR
3819 /*
3820 * Sequence of picks finished successfully; cleanup by
3821 * removing the .git/sequencer directory
3822 */
2863584f 3823 return sequencer_remove_state(opts);
043a4492
RR
3824}
3825
005af339 3826static int continue_single_pick(struct repository *r)
043a4492
RR
3827{
3828 const char *argv[] = { "commit", NULL };
3829
005af339
NTND
3830 if (!file_exists(git_path_cherry_pick_head(r)) &&
3831 !file_exists(git_path_revert_head(r)))
043a4492
RR
3832 return error(_("no cherry-pick or revert in progress"));
3833 return run_command_v_opt(argv, RUN_GIT_CMD);
3834}
3835
f11c9580
NTND
3836static int commit_staged_changes(struct repository *r,
3837 struct replay_opts *opts,
15ef6931 3838 struct todo_list *todo_list)
9d93ccd1 3839{
789b3eff 3840 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
15ef6931 3841 unsigned int final_fixup = 0, is_clean;
9d93ccd1 3842
f11c9580 3843 if (has_unstaged_changes(r, 1))
9d93ccd1 3844 return error(_("cannot rebase: You have unstaged changes."));
52632209 3845
f11c9580 3846 is_clean = !has_uncommitted_changes(r, 0);
9d93ccd1
JS
3847
3848 if (file_exists(rebase_path_amend())) {
3849 struct strbuf rev = STRBUF_INIT;
092bbcdf 3850 struct object_id head, to_amend;
9d93ccd1 3851
092bbcdf 3852 if (get_oid("HEAD", &head))
9d93ccd1
JS
3853 return error(_("cannot amend non-existing commit"));
3854 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3855 return error(_("invalid file: '%s'"), rebase_path_amend());
092bbcdf 3856 if (get_oid_hex(rev.buf, &to_amend))
9d93ccd1
JS
3857 return error(_("invalid contents: '%s'"),
3858 rebase_path_amend());
9001dc2a 3859 if (!is_clean && !oideq(&head, &to_amend))
9d93ccd1
JS
3860 return error(_("\nYou have uncommitted changes in your "
3861 "working tree. Please, commit them\n"
3862 "first and then run 'git rebase "
3863 "--continue' again."));
15ef6931
JS
3864 /*
3865 * When skipping a failed fixup/squash, we need to edit the
3866 * commit message, the current fixup list and count, and if it
3867 * was the last fixup/squash in the chain, we need to clean up
3868 * the commit message and if there was a squash, let the user
3869 * edit it.
3870 */
10d2f354
JS
3871 if (!is_clean || !opts->current_fixup_count)
3872 ; /* this is not the final fixup */
87ae8a1a 3873 else if (!oideq(&head, &to_amend) ||
10d2f354
JS
3874 !file_exists(rebase_path_stopped_sha())) {
3875 /* was a final fixup or squash done manually? */
3876 if (!is_fixup(peek_command(todo_list, 0))) {
3877 unlink(rebase_path_fixup_msg());
3878 unlink(rebase_path_squash_msg());
3879 unlink(rebase_path_current_fixups());
3880 strbuf_reset(&opts->current_fixups);
3881 opts->current_fixup_count = 0;
3882 }
3883 } else {
3884 /* we are in a fixup/squash chain */
15ef6931
JS
3885 const char *p = opts->current_fixups.buf;
3886 int len = opts->current_fixups.len;
3887
3888 opts->current_fixup_count--;
3889 if (!len)
3890 BUG("Incorrect current_fixups:\n%s", p);
3891 while (len && p[len - 1] != '\n')
3892 len--;
3893 strbuf_setlen(&opts->current_fixups, len);
3894 if (write_message(p, len, rebase_path_current_fixups(),
3895 0) < 0)
3896 return error(_("could not write file: '%s'"),
3897 rebase_path_current_fixups());
3898
3899 /*
3900 * If a fixup/squash in a fixup/squash chain failed, the
3901 * commit message is already correct, no need to commit
3902 * it again.
3903 *
3904 * Only if it is the final command in the fixup/squash
3905 * chain, and only if the chain is longer than a single
3906 * fixup/squash command (which was just skipped), do we
3907 * actually need to re-commit with a cleaned up commit
3908 * message.
3909 */
3910 if (opts->current_fixup_count > 0 &&
3911 !is_fixup(peek_command(todo_list, 0))) {
3912 final_fixup = 1;
3913 /*
3914 * If there was not a single "squash" in the
3915 * chain, we only need to clean up the commit
3916 * message, no need to bother the user with
3917 * opening the commit message in the editor.
3918 */
3919 if (!starts_with(p, "squash ") &&
3920 !strstr(p, "\nsquash "))
3921 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
3922 } else if (is_fixup(peek_command(todo_list, 0))) {
3923 /*
3924 * We need to update the squash message to skip
3925 * the latest commit message.
3926 */
3927 struct commit *commit;
3928 const char *path = rebase_path_squash_msg();
3929
005af339 3930 if (parse_head(r, &commit) ||
15ef6931
JS
3931 !(p = get_commit_buffer(commit, NULL)) ||
3932 write_message(p, strlen(p), path, 0)) {
3933 unuse_commit_buffer(commit, p);
3934 return error(_("could not write file: "
3935 "'%s'"), path);
3936 }
3937 unuse_commit_buffer(commit, p);
3938 }
3939 }
9d93ccd1
JS
3940
3941 strbuf_release(&rev);
789b3eff 3942 flags |= AMEND_MSG;
9d93ccd1
JS
3943 }
3944
15ef6931 3945 if (is_clean) {
f11c9580 3946 const char *cherry_pick_head = git_path_cherry_pick_head(r);
15ef6931
JS
3947
3948 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3949 return error(_("could not remove CHERRY_PICK_HEAD"));
3950 if (!final_fixup)
3951 return 0;
3952 }
3953
f11c9580 3954 if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
15ef6931 3955 opts, flags))
9d93ccd1
JS
3956 return error(_("could not commit staged changes."));
3957 unlink(rebase_path_amend());
69c92209 3958 unlink(git_path_merge_head(the_repository));
15ef6931
JS
3959 if (final_fixup) {
3960 unlink(rebase_path_fixup_msg());
3961 unlink(rebase_path_squash_msg());
3962 }
3963 if (opts->current_fixup_count > 0) {
3964 /*
3965 * Whether final fixup or not, we just cleaned up the commit
3966 * message...
3967 */
3968 unlink(rebase_path_current_fixups());
3969 strbuf_reset(&opts->current_fixups);
3970 opts->current_fixup_count = 0;
3971 }
9d93ccd1
JS
3972 return 0;
3973}
3974
f11c9580 3975int sequencer_continue(struct repository *r, struct replay_opts *opts)
043a4492 3976{
004fefa7
JS
3977 struct todo_list todo_list = TODO_LIST_INIT;
3978 int res;
043a4492 3979
f11c9580 3980 if (read_and_refresh_cache(r, opts))
2863584f
JS
3981 return -1;
3982
15ef6931
JS
3983 if (read_populate_opts(opts))
3984 return -1;
9d93ccd1 3985 if (is_rebase_i(opts)) {
005af339 3986 if ((res = read_populate_todo(r, &todo_list, opts)))
15ef6931 3987 goto release_todo_list;
f11c9580 3988 if (commit_staged_changes(r, opts, &todo_list))
9d93ccd1 3989 return -1;
4258a6da 3990 } else if (!file_exists(get_todo_path(opts)))
005af339
NTND
3991 return continue_single_pick(r);
3992 else if ((res = read_populate_todo(r, &todo_list, opts)))
004fefa7 3993 goto release_todo_list;
043a4492 3994
4258a6da
JS
3995 if (!is_rebase_i(opts)) {
3996 /* Verify that the conflict has been resolved */
f11c9580
NTND
3997 if (file_exists(git_path_cherry_pick_head(r)) ||
3998 file_exists(git_path_revert_head(r))) {
005af339 3999 res = continue_single_pick(r);
4258a6da
JS
4000 if (res)
4001 goto release_todo_list;
4002 }
ffc00a48 4003 if (index_differs_from(r, "HEAD", NULL, 0)) {
e1ff0a32 4004 res = error_dirty_index(r, opts);
004fefa7 4005 goto release_todo_list;
4258a6da
JS
4006 }
4007 todo_list.current++;
ca98c6d4
JS
4008 } else if (file_exists(rebase_path_stopped_sha())) {
4009 struct strbuf buf = STRBUF_INIT;
4010 struct object_id oid;
4011
4012 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
e82caf38 4013 !get_oid_committish(buf.buf, &oid))
ca98c6d4
JS
4014 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4015 strbuf_release(&buf);
043a4492 4016 }
4258a6da 4017
f11c9580 4018 res = pick_commits(r, &todo_list, opts);
004fefa7
JS
4019release_todo_list:
4020 todo_list_release(&todo_list);
4021 return res;
043a4492
RR
4022}
4023
f11c9580
NTND
4024static int single_pick(struct repository *r,
4025 struct commit *cmit,
4026 struct replay_opts *opts)
043a4492
RR
4027{
4028 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
f11c9580 4029 return do_pick_commit(r, opts->action == REPLAY_PICK ?
6e98de72 4030 TODO_PICK : TODO_REVERT, cmit, opts, 0);
043a4492
RR
4031}
4032
f11c9580
NTND
4033int sequencer_pick_revisions(struct repository *r,
4034 struct replay_opts *opts)
043a4492 4035{
004fefa7 4036 struct todo_list todo_list = TODO_LIST_INIT;
1e43ed98 4037 struct object_id oid;
004fefa7 4038 int i, res;
043a4492 4039
2863584f 4040 assert(opts->revs);
f11c9580 4041 if (read_and_refresh_cache(r, opts))
0d9c6dc9 4042 return -1;
043a4492 4043
21246dbb 4044 for (i = 0; i < opts->revs->pending.nr; i++) {
1e43ed98 4045 struct object_id oid;
21246dbb
MV
4046 const char *name = opts->revs->pending.objects[i].name;
4047
4048 /* This happens when using --stdin. */
4049 if (!strlen(name))
4050 continue;
4051
1e43ed98 4052 if (!get_oid(name, &oid)) {
f11c9580
NTND
4053 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4054 enum object_type type = oid_object_info(r,
0df8e965 4055 &oid,
abef9020 4056 NULL);
b9b946d4 4057 return error(_("%s: can't cherry-pick a %s"),
debca9d2 4058 name, type_name(type));
7c0b0d8d 4059 }
21246dbb 4060 } else
b9b946d4 4061 return error(_("%s: bad revision"), name);
21246dbb
MV
4062 }
4063
043a4492
RR
4064 /*
4065 * If we were called as "git cherry-pick <commit>", just
4066 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4067 * REVERT_HEAD, and don't touch the sequencer state.
4068 * This means it is possible to cherry-pick in the middle
4069 * of a cherry-pick sequence.
4070 */
4071 if (opts->revs->cmdline.nr == 1 &&
4072 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4073 opts->revs->no_walk &&
4074 !opts->revs->cmdline.rev->flags) {
4075 struct commit *cmit;
4076 if (prepare_revision_walk(opts->revs))
b9b946d4 4077 return error(_("revision walk setup failed"));
043a4492 4078 cmit = get_revision(opts->revs);
c5e358d0
JK
4079 if (!cmit)
4080 return error(_("empty commit set passed"));
4081 if (get_revision(opts->revs))
4082 BUG("unexpected extra commit from walk");
f11c9580 4083 return single_pick(r, cmit, opts);
043a4492
RR
4084 }
4085
4086 /*
4087 * Start a new cherry-pick/ revert sequence; but
4088 * first, make sure that an existing one isn't in
4089 * progress
4090 */
4091
34b0528b
JS
4092 if (walk_revs_populate_todo(&todo_list, opts) ||
4093 create_seq_dir() < 0)
043a4492 4094 return -1;
1e43ed98 4095 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
93b3df6f 4096 return error(_("can't revert as initial commit"));
1e43ed98 4097 if (save_head(oid_to_hex(&oid)))
311fd397 4098 return -1;
88d5a271
JS
4099 if (save_opts(opts))
4100 return -1;
1e41229d 4101 update_abort_safety_file();
f11c9580 4102 res = pick_commits(r, &todo_list, opts);
004fefa7
JS
4103 todo_list_release(&todo_list);
4104 return res;
043a4492 4105}
5ed75e2a 4106
66e83d9b 4107void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5ed75e2a 4108{
bab4d109 4109 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5ed75e2a 4110 struct strbuf sob = STRBUF_INIT;
bab4d109 4111 int has_footer;
5ed75e2a
MV
4112
4113 strbuf_addstr(&sob, sign_off_header);
39ab4d09 4114 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5ed75e2a 4115 strbuf_addch(&sob, '\n');
bab4d109 4116
44dc738a
JT
4117 if (!ignore_footer)
4118 strbuf_complete_line(msgbuf);
4119
bab4d109
BC
4120 /*
4121 * If the whole message buffer is equal to the sob, pretend that we
4122 * found a conforming footer with a matching sob
4123 */
4124 if (msgbuf->len - ignore_footer == sob.len &&
4125 !strncmp(msgbuf->buf, sob.buf, sob.len))
4126 has_footer = 3;
4127 else
4128 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4129
33f2f9ab
BC
4130 if (!has_footer) {
4131 const char *append_newlines = NULL;
4132 size_t len = msgbuf->len - ignore_footer;
4133
8c613fd5
BC
4134 if (!len) {
4135 /*
4136 * The buffer is completely empty. Leave foom for
4137 * the title and body to be filled in by the user.
4138 */
33f2f9ab 4139 append_newlines = "\n\n";
8c613fd5
BC
4140 } else if (len == 1) {
4141 /*
4142 * Buffer contains a single newline. Add another
4143 * so that we leave room for the title and body.
4144 */
4145 append_newlines = "\n";
4146 } else if (msgbuf->buf[len - 2] != '\n') {
4147 /*
4148 * Buffer ends with a single newline. Add another
4149 * so that there is an empty line between the message
4150 * body and the sob.
4151 */
33f2f9ab 4152 append_newlines = "\n";
8c613fd5 4153 } /* else, the buffer already ends with two newlines. */
33f2f9ab
BC
4154
4155 if (append_newlines)
4156 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4157 append_newlines, strlen(append_newlines));
5ed75e2a 4158 }
bab4d109
BC
4159
4160 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4161 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4162 sob.buf, sob.len);
4163
5ed75e2a
MV
4164 strbuf_release(&sob);
4165}
62db5247 4166
1644c73c
JS
4167struct labels_entry {
4168 struct hashmap_entry entry;
4169 char label[FLEX_ARRAY];
4170};
4171
4172static int labels_cmp(const void *fndata, const struct labels_entry *a,
4173 const struct labels_entry *b, const void *key)
4174{
4175 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4176}
4177
4178struct string_entry {
4179 struct oidmap_entry entry;
4180 char string[FLEX_ARRAY];
4181};
4182
4183struct label_state {
4184 struct oidmap commit2label;
4185 struct hashmap labels;
4186 struct strbuf buf;
4187};
4188
4189static const char *label_oid(struct object_id *oid, const char *label,
4190 struct label_state *state)
4191{
4192 struct labels_entry *labels_entry;
4193 struct string_entry *string_entry;
4194 struct object_id dummy;
4195 size_t len;
4196 int i;
4197
4198 string_entry = oidmap_get(&state->commit2label, oid);
4199 if (string_entry)
4200 return string_entry->string;
4201
4202 /*
4203 * For "uninteresting" commits, i.e. commits that are not to be
4204 * rebased, and which can therefore not be labeled, we use a unique
4205 * abbreviation of the commit name. This is slightly more complicated
4206 * than calling find_unique_abbrev() because we also need to make
4207 * sure that the abbreviation does not conflict with any other
4208 * label.
4209 *
4210 * We disallow "interesting" commits to be labeled by a string that
4211 * is a valid full-length hash, to ensure that we always can find an
4212 * abbreviation for any uninteresting commit's names that does not
4213 * clash with any other label.
4214 */
4215 if (!label) {
4216 char *p;
4217
4218 strbuf_reset(&state->buf);
4219 strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
4220 label = p = state->buf.buf;
4221
4222 find_unique_abbrev_r(p, oid, default_abbrev);
4223
4224 /*
4225 * We may need to extend the abbreviated hash so that there is
4226 * no conflicting label.
4227 */
4228 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4229 size_t i = strlen(p) + 1;
4230
4231 oid_to_hex_r(p, oid);
4232 for (; i < GIT_SHA1_HEXSZ; i++) {
4233 char save = p[i];
4234 p[i] = '\0';
4235 if (!hashmap_get_from_hash(&state->labels,
4236 strihash(p), p))
4237 break;
4238 p[i] = save;
4239 }
4240 }
5971b083 4241 } else if (((len = strlen(label)) == the_hash_algo->hexsz &&
1644c73c
JS
4242 !get_oid_hex(label, &dummy)) ||
4243 (len == 1 && *label == '#') ||
4244 hashmap_get_from_hash(&state->labels,
4245 strihash(label), label)) {
4246 /*
4247 * If the label already exists, or if the label is a valid full
4248 * OID, or the label is a '#' (which we use as a separator
4249 * between merge heads and oneline), we append a dash and a
4250 * number to make it unique.
4251 */
4252 struct strbuf *buf = &state->buf;
4253
4254 strbuf_reset(buf);
4255 strbuf_add(buf, label, len);
4256
4257 for (i = 2; ; i++) {
4258 strbuf_setlen(buf, len);
4259 strbuf_addf(buf, "-%d", i);
4260 if (!hashmap_get_from_hash(&state->labels,
4261 strihash(buf->buf),
4262 buf->buf))
4263 break;
4264 }
4265
4266 label = buf->buf;
4267 }
4268
4269 FLEX_ALLOC_STR(labels_entry, label, label);
4270 hashmap_entry_init(labels_entry, strihash(label));
4271 hashmap_add(&state->labels, labels_entry);
4272
4273 FLEX_ALLOC_STR(string_entry, string, label);
4274 oidcpy(&string_entry->entry.oid, oid);
4275 oidmap_put(&state->commit2label, string_entry);
4276
4277 return string_entry->string;
4278}
4279
4280static int make_script_with_merges(struct pretty_print_context *pp,
4281 struct rev_info *revs, FILE *out,
4282 unsigned flags)
4283{
4284 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
7543f6f4 4285 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
1644c73c
JS
4286 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4287 struct strbuf label = STRBUF_INIT;
4288 struct commit_list *commits = NULL, **tail = &commits, *iter;
4289 struct commit_list *tips = NULL, **tips_tail = &tips;
4290 struct commit *commit;
4291 struct oidmap commit2todo = OIDMAP_INIT;
4292 struct string_entry *entry;
4293 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4294 shown = OIDSET_INIT;
4295 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4296
4297 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4298 const char *cmd_pick = abbr ? "p" : "pick",
4299 *cmd_label = abbr ? "l" : "label",
4300 *cmd_reset = abbr ? "t" : "reset",
4301 *cmd_merge = abbr ? "m" : "merge";
4302
4303 oidmap_init(&commit2todo, 0);
4304 oidmap_init(&state.commit2label, 0);
4305 hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
4306 strbuf_init(&state.buf, 32);
4307
4308 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4309 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4310 FLEX_ALLOC_STR(entry, string, "onto");
4311 oidcpy(&entry->entry.oid, oid);
4312 oidmap_put(&state.commit2label, entry);
4313 }
4314
4315 /*
4316 * First phase:
4317 * - get onelines for all commits
4318 * - gather all branch tips (i.e. 2nd or later parents of merges)
4319 * - label all branch tips
4320 */
4321 while ((commit = get_revision(revs))) {
4322 struct commit_list *to_merge;
1644c73c
JS
4323 const char *p1, *p2;
4324 struct object_id *oid;
4325 int is_empty;
4326
4327 tail = &commit_list_insert(commit, tail)->next;
4328 oidset_insert(&interesting, &commit->object.oid);
4329
4330 is_empty = is_original_commit_empty(commit);
4331 if (!is_empty && (commit->object.flags & PATCHSAME))
4332 continue;
4333
4334 strbuf_reset(&oneline);
4335 pretty_print_commit(pp, commit, &oneline);
4336
4337 to_merge = commit->parents ? commit->parents->next : NULL;
4338 if (!to_merge) {
4339 /* non-merge commit: easy case */
4340 strbuf_reset(&buf);
4341 if (!keep_empty && is_empty)
4342 strbuf_addf(&buf, "%c ", comment_line_char);
4343 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4344 oid_to_hex(&commit->object.oid),
4345 oneline.buf);
4346
4347 FLEX_ALLOC_STR(entry, string, buf.buf);
4348 oidcpy(&entry->entry.oid, &commit->object.oid);
4349 oidmap_put(&commit2todo, entry);
4350
4351 continue;
4352 }
4353
1644c73c
JS
4354 /* Create a label */
4355 strbuf_reset(&label);
4356 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4357 (p1 = strchr(p1, '\'')) &&
4358 (p2 = strchr(++p1, '\'')))
4359 strbuf_add(&label, p1, p2 - p1);
4360 else if (skip_prefix(oneline.buf, "Merge pull request ",
4361 &p1) &&
4362 (p1 = strstr(p1, " from ")))
4363 strbuf_addstr(&label, p1 + strlen(" from "));
4364 else
4365 strbuf_addbuf(&label, &oneline);
4366
4367 for (p1 = label.buf; *p1; p1++)
4368 if (isspace(*p1))
4369 *(char *)p1 = '-';
4370
4371 strbuf_reset(&buf);
4372 strbuf_addf(&buf, "%s -C %s",
4373 cmd_merge, oid_to_hex(&commit->object.oid));
4374
2b6ad0f4
JS
4375 /* label the tips of merged branches */
4376 for (; to_merge; to_merge = to_merge->next) {
4377 oid = &to_merge->item->object.oid;
4378 strbuf_addch(&buf, ' ');
4379
4380 if (!oidset_contains(&interesting, oid)) {
4381 strbuf_addstr(&buf, label_oid(oid, NULL,
4382 &state));
4383 continue;
4384 }
1644c73c 4385
1644c73c
JS
4386 tips_tail = &commit_list_insert(to_merge->item,
4387 tips_tail)->next;
4388
4389 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4390 }
4391 strbuf_addf(&buf, " # %s", oneline.buf);
4392
4393 FLEX_ALLOC_STR(entry, string, buf.buf);
4394 oidcpy(&entry->entry.oid, &commit->object.oid);
4395 oidmap_put(&commit2todo, entry);
4396 }
4397
4398 /*
4399 * Second phase:
4400 * - label branch points
4401 * - add HEAD to the branch tips
4402 */
4403 for (iter = commits; iter; iter = iter->next) {
4404 struct commit_list *parent = iter->item->parents;
4405 for (; parent; parent = parent->next) {
4406 struct object_id *oid = &parent->item->object.oid;
4407 if (!oidset_contains(&interesting, oid))
4408 continue;
6e8fc70f 4409 if (oidset_insert(&child_seen, oid))
1644c73c
JS
4410 label_oid(oid, "branch-point", &state);
4411 }
4412
4413 /* Add HEAD as implict "tip of branch" */
4414 if (!iter->next)
4415 tips_tail = &commit_list_insert(iter->item,
4416 tips_tail)->next;
4417 }
4418
4419 /*
4420 * Third phase: output the todo list. This is a bit tricky, as we
4421 * want to avoid jumping back and forth between revisions. To
4422 * accomplish that goal, we walk backwards from the branch tips,
4423 * gathering commits not yet shown, reversing the list on the fly,
4424 * then outputting that list (labeling revisions as needed).
4425 */
4426 fprintf(out, "%s onto\n", cmd_label);
4427 for (iter = tips; iter; iter = iter->next) {
4428 struct commit_list *list = NULL, *iter2;
4429
4430 commit = iter->item;
4431 if (oidset_contains(&shown, &commit->object.oid))
4432 continue;
4433 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4434
4435 if (entry)
02cfd149 4436 fprintf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
1644c73c
JS
4437 else
4438 fprintf(out, "\n");
4439
4440 while (oidset_contains(&interesting, &commit->object.oid) &&
4441 !oidset_contains(&shown, &commit->object.oid)) {
4442 commit_list_insert(commit, &list);
4443 if (!commit->parents) {
4444 commit = NULL;
4445 break;
4446 }
4447 commit = commit->parents->item;
4448 }
4449
4450 if (!commit)
8fa6eea0
JS
4451 fprintf(out, "%s %s\n", cmd_reset,
4452 rebase_cousins ? "onto" : "[new root]");
1644c73c
JS
4453 else {
4454 const char *to = NULL;
4455
4456 entry = oidmap_get(&state.commit2label,
4457 &commit->object.oid);
4458 if (entry)
4459 to = entry->string;
7543f6f4
JS
4460 else if (!rebase_cousins)
4461 to = label_oid(&commit->object.oid, NULL,
4462 &state);
1644c73c
JS
4463
4464 if (!to || !strcmp(to, "onto"))
4465 fprintf(out, "%s onto\n", cmd_reset);
4466 else {
4467 strbuf_reset(&oneline);
4468 pretty_print_commit(pp, commit, &oneline);
4469 fprintf(out, "%s %s # %s\n",
4470 cmd_reset, to, oneline.buf);
4471 }
4472 }
4473
4474 for (iter2 = list; iter2; iter2 = iter2->next) {
4475 struct object_id *oid = &iter2->item->object.oid;
4476 entry = oidmap_get(&commit2todo, oid);
4477 /* only show if not already upstream */
4478 if (entry)
4479 fprintf(out, "%s\n", entry->string);
4480 entry = oidmap_get(&state.commit2label, oid);
4481 if (entry)
4482 fprintf(out, "%s %s\n",
4483 cmd_label, entry->string);
4484 oidset_insert(&shown, oid);
4485 }
4486
4487 free_commit_list(list);
4488 }
4489
4490 free_commit_list(commits);
4491 free_commit_list(tips);
4492
4493 strbuf_release(&label);
4494 strbuf_release(&oneline);
4495 strbuf_release(&buf);
4496
4497 oidmap_free(&commit2todo, 1);
4498 oidmap_free(&state.commit2label, 1);
4499 hashmap_free(&state.labels, 1);
4500 strbuf_release(&state.buf);
4501
4502 return 0;
4503}
4504
f11c9580
NTND
4505int sequencer_make_script(struct repository *r, FILE *out,
4506 int argc, const char **argv,
313a48ea 4507 unsigned flags)
62db5247
JS
4508{
4509 char *format = NULL;
4510 struct pretty_print_context pp = {0};
4511 struct strbuf buf = STRBUF_INIT;
4512 struct rev_info revs;
4513 struct commit *commit;
313a48ea 4514 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
d8ae6c84 4515 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
1644c73c 4516 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
62db5247 4517
f11c9580 4518 repo_init_revisions(r, &revs, NULL);
62db5247 4519 revs.verbose_header = 1;
1644c73c
JS
4520 if (!rebase_merges)
4521 revs.max_parents = 1;
76ea2358 4522 revs.cherry_mark = 1;
62db5247
JS
4523 revs.limited = 1;
4524 revs.reverse = 1;
4525 revs.right_only = 1;
4526 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4527 revs.topo_order = 1;
4528
4529 revs.pretty_given = 1;
4530 git_config_get_string("rebase.instructionFormat", &format);
4531 if (!format || !*format) {
4532 free(format);
4533 format = xstrdup("%s");
4534 }
4535 get_commit_format(format, &revs);
4536 free(format);
4537 pp.fmt = revs.commit_format;
4538 pp.output_encoding = get_log_output_encoding();
4539
4540 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4541 return error(_("make_script: unhandled options"));
4542
4543 if (prepare_revision_walk(&revs) < 0)
4544 return error(_("make_script: error preparing revisions"));
4545
1644c73c
JS
4546 if (rebase_merges)
4547 return make_script_with_merges(&pp, &revs, out, flags);
4548
62db5247 4549 while ((commit = get_revision(&revs))) {
76ea2358
PW
4550 int is_empty = is_original_commit_empty(commit);
4551
4552 if (!is_empty && (commit->object.flags & PATCHSAME))
4553 continue;
62db5247 4554 strbuf_reset(&buf);
76ea2358 4555 if (!keep_empty && is_empty)
62db5247 4556 strbuf_addf(&buf, "%c ", comment_line_char);
d8ae6c84
LB
4557 strbuf_addf(&buf, "%s %s ", insn,
4558 oid_to_hex(&commit->object.oid));
62db5247
JS
4559 pretty_print_commit(&pp, commit, &buf);
4560 strbuf_addch(&buf, '\n');
4561 fputs(buf.buf, out);
4562 }
4563 strbuf_release(&buf);
4564 return 0;
4565}
3546c8d9 4566
0cce4a27
LB
4567/*
4568 * Add commands after pick and (series of) squash/fixup commands
4569 * in the todo list.
4570 */
005af339
NTND
4571int sequencer_add_exec_commands(struct repository *r,
4572 const char *commands)
3546c8d9
JS
4573{
4574 const char *todo_file = rebase_path_todo();
4575 struct todo_list todo_list = TODO_LIST_INIT;
0cce4a27
LB
4576 struct strbuf *buf = &todo_list.buf;
4577 size_t offset = 0, commands_len = strlen(commands);
1ace63bc 4578 int i, insert;
3546c8d9 4579
0cce4a27 4580 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3546c8d9 4581 return error(_("could not read '%s'."), todo_file);
3546c8d9 4582
005af339 4583 if (parse_insn_buffer(r, todo_list.buf.buf, &todo_list)) {
3546c8d9
JS
4584 todo_list_release(&todo_list);
4585 return error(_("unusable todo list: '%s'"), todo_file);
4586 }
4587
1ace63bc
JS
4588 /*
4589 * Insert <commands> after every pick. Here, fixup/squash chains
4590 * are considered part of the pick, so we insert the commands *after*
4591 * those chains if there are any.
4592 */
4593 insert = -1;
4594 for (i = 0; i < todo_list.nr; i++) {
4595 enum todo_command command = todo_list.items[i].command;
4596
4597 if (insert >= 0) {
4598 /* skip fixup/squash chains */
4599 if (command == TODO_COMMENT)
4600 continue;
4601 else if (is_fixup(command)) {
4602 insert = i + 1;
4603 continue;
4604 }
4605 strbuf_insert(buf,
4606 todo_list.items[insert].offset_in_buf +
4607 offset, commands, commands_len);
0cce4a27 4608 offset += commands_len;
1ace63bc 4609 insert = -1;
0cce4a27 4610 }
1ace63bc
JS
4611
4612 if (command == TODO_PICK || command == TODO_MERGE)
4613 insert = i + 1;
0cce4a27
LB
4614 }
4615
1ace63bc
JS
4616 /* insert or append final <commands> */
4617 if (insert >= 0 && insert < todo_list.nr)
4618 strbuf_insert(buf, todo_list.items[insert].offset_in_buf +
4619 offset, commands, commands_len);
4620 else if (insert >= 0 || !offset)
4621 strbuf_add(buf, commands, commands_len);
0cce4a27
LB
4622
4623 i = write_message(buf->buf, buf->len, todo_file, 0);
4624 todo_list_release(&todo_list);
4625 return i;
4626}
3546c8d9 4627
005af339 4628int transform_todos(struct repository *r, unsigned flags)
3546c8d9
JS
4629{
4630 const char *todo_file = rebase_path_todo();
4631 struct todo_list todo_list = TODO_LIST_INIT;
8dccc7a6
LB
4632 struct strbuf buf = STRBUF_INIT;
4633 struct todo_item *item;
4634 int i;
3546c8d9 4635
8dccc7a6 4636 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3546c8d9 4637 return error(_("could not read '%s'."), todo_file);
3546c8d9 4638
005af339 4639 if (parse_insn_buffer(r, todo_list.buf.buf, &todo_list)) {
3546c8d9 4640 todo_list_release(&todo_list);
3546c8d9
JS
4641 return error(_("unusable todo list: '%s'"), todo_file);
4642 }
4643
8dccc7a6
LB
4644 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
4645 /* if the item is not a command write it and continue */
4646 if (item->command >= TODO_COMMENT) {
4647 strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
4648 continue;
3546c8d9 4649 }
8dccc7a6
LB
4650
4651 /* add command to the buffer */
d8ae6c84
LB
4652 if (flags & TODO_LIST_ABBREVIATE_CMDS)
4653 strbuf_addch(&buf, command_to_char(item->command));
4654 else
4655 strbuf_addstr(&buf, command_to_string(item->command));
8dccc7a6
LB
4656
4657 /* add commit id */
4658 if (item->commit) {
313a48ea 4659 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
8dccc7a6
LB
4660 short_commit_name(item->commit) :
4661 oid_to_hex(&item->commit->object.oid);
4662
4c68e7dd
JS
4663 if (item->command == TODO_MERGE) {
4664 if (item->flags & TODO_EDIT_MERGE_MSG)
4665 strbuf_addstr(&buf, " -c");
4666 else
4667 strbuf_addstr(&buf, " -C");
4668 }
4669
8dccc7a6 4670 strbuf_addf(&buf, " %s", oid);
3546c8d9 4671 }
4c68e7dd 4672
8dccc7a6 4673 /* add all the rest */
c7b4d79c
JS
4674 if (!item->arg_len)
4675 strbuf_addch(&buf, '\n');
4676 else
4677 strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
3546c8d9 4678 }
8dccc7a6
LB
4679
4680 i = write_message(buf.buf, buf.len, todo_file, 0);
3546c8d9 4681 todo_list_release(&todo_list);
8dccc7a6 4682 return i;
3546c8d9 4683}
94399949 4684
44b776c3 4685enum missing_commit_check_level get_missing_commit_check_level(void)
94399949
JS
4686{
4687 const char *value;
4688
4689 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
4690 !strcasecmp("ignore", value))
44b776c3 4691 return MISSING_COMMIT_CHECK_IGNORE;
94399949 4692 if (!strcasecmp("warn", value))
44b776c3 4693 return MISSING_COMMIT_CHECK_WARN;
94399949 4694 if (!strcasecmp("error", value))
44b776c3 4695 return MISSING_COMMIT_CHECK_ERROR;
dfab1eac 4696 warning(_("unrecognized setting %s for option "
94399949 4697 "rebase.missingCommitsCheck. Ignoring."), value);
44b776c3 4698 return MISSING_COMMIT_CHECK_IGNORE;
94399949
JS
4699}
4700
8315bd20 4701define_commit_slab(commit_seen, unsigned char);
94399949
JS
4702/*
4703 * Check if the user dropped some commits by mistake
4704 * Behaviour determined by rebase.missingCommitsCheck.
4705 * Check if there is an unrecognized command or a
4706 * bad SHA-1 in a command.
4707 */
005af339 4708int check_todo_list(struct repository *r)
94399949 4709{
44b776c3 4710 enum missing_commit_check_level check_level = get_missing_commit_check_level();
94399949
JS
4711 struct strbuf todo_file = STRBUF_INIT;
4712 struct todo_list todo_list = TODO_LIST_INIT;
4713 struct strbuf missing = STRBUF_INIT;
87805600 4714 int advise_to_edit_todo = 0, res = 0, i;
8315bd20
NTND
4715 struct commit_seen commit_seen;
4716
4717 init_commit_seen(&commit_seen);
94399949
JS
4718
4719 strbuf_addstr(&todo_file, rebase_path_todo());
87805600
RS
4720 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4721 res = -1;
94399949
JS
4722 goto leave_check;
4723 }
94399949 4724 advise_to_edit_todo = res =
005af339 4725 parse_insn_buffer(r, todo_list.buf.buf, &todo_list);
94399949 4726
44b776c3 4727 if (res || check_level == MISSING_COMMIT_CHECK_IGNORE)
94399949
JS
4728 goto leave_check;
4729
4730 /* Mark the commits in git-rebase-todo as seen */
4731 for (i = 0; i < todo_list.nr; i++) {
4732 struct commit *commit = todo_list.items[i].commit;
4733 if (commit)
8315bd20 4734 *commit_seen_at(&commit_seen, commit) = 1;
94399949
JS
4735 }
4736
4737 todo_list_release(&todo_list);
4738 strbuf_addstr(&todo_file, ".backup");
87805600
RS
4739 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4740 res = -1;
94399949
JS
4741 goto leave_check;
4742 }
94399949 4743 strbuf_release(&todo_file);
005af339 4744 res = !!parse_insn_buffer(r, todo_list.buf.buf, &todo_list);
94399949
JS
4745
4746 /* Find commits in git-rebase-todo.backup yet unseen */
4747 for (i = todo_list.nr - 1; i >= 0; i--) {
4748 struct todo_item *item = todo_list.items + i;
4749 struct commit *commit = item->commit;
8315bd20 4750 if (commit && !*commit_seen_at(&commit_seen, commit)) {
94399949
JS
4751 strbuf_addf(&missing, " - %s %.*s\n",
4752 short_commit_name(commit),
4753 item->arg_len, item->arg);
8315bd20 4754 *commit_seen_at(&commit_seen, commit) = 1;
94399949
JS
4755 }
4756 }
4757
4758 /* Warn about missing commits */
4759 if (!missing.len)
4760 goto leave_check;
4761
44b776c3 4762 if (check_level == MISSING_COMMIT_CHECK_ERROR)
94399949
JS
4763 advise_to_edit_todo = res = 1;
4764
4765 fprintf(stderr,
4766 _("Warning: some commits may have been dropped accidentally.\n"
4767 "Dropped commits (newer to older):\n"));
4768
4769 /* Make the list user-friendly and display */
4770 fputs(missing.buf, stderr);
4771 strbuf_release(&missing);
4772
4773 fprintf(stderr, _("To avoid this message, use \"drop\" to "
4774 "explicitly remove a commit.\n\n"
4775 "Use 'git config rebase.missingCommitsCheck' to change "
4776 "the level of warnings.\n"
4777 "The possible behaviours are: ignore, warn, error.\n\n"));
4778
4779leave_check:
8315bd20 4780 clear_commit_seen(&commit_seen);
94399949
JS
4781 strbuf_release(&todo_file);
4782 todo_list_release(&todo_list);
4783
4784 if (advise_to_edit_todo)
4785 fprintf(stderr,
4786 _("You can fix this with 'git rebase --edit-todo' "
4787 "and then run 'git rebase --continue'.\n"
4788 "Or you can abort the rebase with 'git rebase"
4789 " --abort'.\n"));
4790
4791 return res;
4792}
cdac2b01 4793
73646bfd
RS
4794static int rewrite_file(const char *path, const char *buf, size_t len)
4795{
4796 int rc = 0;
c8cee96e 4797 int fd = open(path, O_WRONLY | O_TRUNC);
73646bfd
RS
4798 if (fd < 0)
4799 return error_errno(_("could not open '%s' for writing"), path);
4800 if (write_in_full(fd, buf, len) < 0)
4801 rc = error_errno(_("could not write to '%s'"), path);
9360ec00
SR
4802 if (close(fd) && !rc)
4803 rc = error_errno(_("could not close '%s'"), path);
73646bfd
RS
4804 return rc;
4805}
4806
cdac2b01 4807/* skip picking commits whose parents are unchanged */
005af339 4808static int skip_unnecessary_picks(struct repository *r, struct object_id *output_oid)
cdac2b01
JS
4809{
4810 const char *todo_file = rebase_path_todo();
4811 struct strbuf buf = STRBUF_INIT;
4812 struct todo_list todo_list = TODO_LIST_INIT;
d4ed5d77 4813 struct object_id *parent_oid;
cdac2b01
JS
4814 int fd, i;
4815
4816 if (!read_oneliner(&buf, rebase_path_onto(), 0))
4817 return error(_("could not read 'onto'"));
d4ed5d77 4818 if (get_oid(buf.buf, output_oid)) {
cdac2b01
JS
4819 strbuf_release(&buf);
4820 return error(_("need a HEAD to fixup"));
4821 }
4822 strbuf_release(&buf);
4823
87805600
RS
4824 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4825 return -1;
005af339 4826 if (parse_insn_buffer(r, todo_list.buf.buf, &todo_list) < 0) {
cdac2b01
JS
4827 todo_list_release(&todo_list);
4828 return -1;
4829 }
4830
4831 for (i = 0; i < todo_list.nr; i++) {
4832 struct todo_item *item = todo_list.items + i;
4833
4834 if (item->command >= TODO_NOOP)
4835 continue;
4836 if (item->command != TODO_PICK)
4837 break;
4838 if (parse_commit(item->commit)) {
4839 todo_list_release(&todo_list);
4840 return error(_("could not parse commit '%s'"),
4841 oid_to_hex(&item->commit->object.oid));
4842 }
4843 if (!item->commit->parents)
4844 break; /* root commit */
4845 if (item->commit->parents->next)
4846 break; /* merge commit */
4847 parent_oid = &item->commit->parents->item->object.oid;
b49ef560 4848 if (!oideq(parent_oid, output_oid))
cdac2b01 4849 break;
d4ed5d77 4850 oidcpy(output_oid, &item->commit->object.oid);
cdac2b01
JS
4851 }
4852 if (i > 0) {
a01c2a5f 4853 int offset = get_item_line_offset(&todo_list, i);
cdac2b01
JS
4854 const char *done_path = rebase_path_done();
4855
4856 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
4857 if (fd < 0) {
4858 error_errno(_("could not open '%s' for writing"),
4859 done_path);
4860 todo_list_release(&todo_list);
4861 return -1;
4862 }
4863 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
4864 error_errno(_("could not write to '%s'"), done_path);
4865 todo_list_release(&todo_list);
4866 close(fd);
4867 return -1;
4868 }
4869 close(fd);
4870
73646bfd
RS
4871 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
4872 todo_list.buf.len - offset) < 0) {
cdac2b01 4873 todo_list_release(&todo_list);
cdac2b01
JS
4874 return -1;
4875 }
cdac2b01
JS
4876
4877 todo_list.current = i;
4878 if (is_fixup(peek_command(&todo_list, 0)))
d4ed5d77 4879 record_in_rewritten(output_oid, peek_command(&todo_list, 0));
cdac2b01
JS
4880 }
4881
4882 todo_list_release(&todo_list);
cdac2b01
JS
4883
4884 return 0;
4885}
c44a4c65 4886
005af339 4887int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
b97e1873
AG
4888 const char *shortrevisions, const char *onto_name,
4889 const char *onto, const char *orig_head, const char *cmd,
4890 unsigned autosquash)
4891{
4892 const char *shortonto, *todo_file = rebase_path_todo();
4893 struct todo_list todo_list = TODO_LIST_INIT;
4894 struct strbuf *buf = &(todo_list.buf);
4895 struct object_id oid;
4896 struct stat st;
4897
4898 get_oid(onto, &oid);
4899 shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
4900
4901 if (!lstat(todo_file, &st) && st.st_size == 0 &&
4902 write_message("noop\n", 5, todo_file, 0))
4903 return -1;
4904
005af339 4905 if (autosquash && rearrange_squash(r))
b97e1873
AG
4906 return -1;
4907
4908 if (cmd && *cmd)
005af339 4909 sequencer_add_exec_commands(r, cmd);
b97e1873
AG
4910
4911 if (strbuf_read_file(buf, todo_file, 0) < 0)
4912 return error_errno(_("could not read '%s'."), todo_file);
4913
005af339 4914 if (parse_insn_buffer(r, buf->buf, &todo_list)) {
b97e1873
AG
4915 todo_list_release(&todo_list);
4916 return error(_("unusable todo list: '%s'"), todo_file);
4917 }
4918
4919 if (count_commands(&todo_list) == 0) {
4920 apply_autostash(opts);
4921 sequencer_remove_state(opts);
4922 todo_list_release(&todo_list);
4923
4924 return error(_("nothing to do"));
4925 }
4926
4927 strbuf_addch(buf, '\n');
4928 strbuf_commented_addf(buf, Q_("Rebase %s onto %s (%d command)",
4929 "Rebase %s onto %s (%d commands)",
4930 count_commands(&todo_list)),
4931 shortrevisions, shortonto, count_commands(&todo_list));
4932 append_todo_help(0, flags & TODO_LIST_KEEP_EMPTY, buf);
4933
4934 if (write_message(buf->buf, buf->len, todo_file, 0)) {
4935 todo_list_release(&todo_list);
4936 return -1;
4937 }
4938
4939 if (copy_file(rebase_path_todo_backup(), todo_file, 0666))
4940 return error(_("could not copy '%s' to '%s'."), todo_file,
4941 rebase_path_todo_backup());
4942
005af339 4943 if (transform_todos(r, flags | TODO_LIST_SHORTEN_IDS))
b97e1873
AG
4944 return error(_("could not transform the todo list"));
4945
4946 strbuf_reset(buf);
4947
4948 if (launch_sequence_editor(todo_file, buf, NULL)) {
4949 apply_autostash(opts);
4950 sequencer_remove_state(opts);
4951 todo_list_release(&todo_list);
4952
4953 return -1;
4954 }
4955
4956 strbuf_stripspace(buf, 1);
4957 if (buf->len == 0) {
4958 apply_autostash(opts);
4959 sequencer_remove_state(opts);
4960 todo_list_release(&todo_list);
4961
4962 return error(_("nothing to do"));
4963 }
4964
4965 todo_list_release(&todo_list);
4966
005af339 4967 if (check_todo_list(r)) {
b97e1873
AG
4968 checkout_onto(opts, onto_name, onto, orig_head);
4969 return -1;
4970 }
4971
005af339 4972 if (transform_todos(r, flags & ~(TODO_LIST_SHORTEN_IDS)))
b97e1873
AG
4973 return error(_("could not transform the todo list"));
4974
005af339 4975 if (opts->allow_ff && skip_unnecessary_picks(r, &oid))
b97e1873
AG
4976 return error(_("could not skip unnecessary pick commands"));
4977
4978 if (checkout_onto(opts, onto_name, oid_to_hex(&oid), orig_head))
4979 return -1;
29d51e21 4980
005af339 4981 if (require_clean_work_tree(r, "rebase", "", 1, 1))
b97e1873
AG
4982 return -1;
4983
005af339 4984 return sequencer_continue(r, opts);
b97e1873
AG
4985}
4986
c44a4c65
JS
4987struct subject2item_entry {
4988 struct hashmap_entry entry;
4989 int i;
4990 char subject[FLEX_ARRAY];
4991};
4992
4993static int subject2item_cmp(const void *fndata,
4994 const struct subject2item_entry *a,
4995 const struct subject2item_entry *b, const void *key)
4996{
4997 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
4998}
4999
3cc0287b
NTND
5000define_commit_slab(commit_todo_item, struct todo_item *);
5001
c44a4c65
JS
5002/*
5003 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5004 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5005 * after the former, and change "pick" to "fixup"/"squash".
5006 *
5007 * Note that if the config has specified a custom instruction format, each log
5008 * message will have to be retrieved from the commit (as the oneline in the
5009 * script cannot be trusted) in order to normalize the autosquash arrangement.
5010 */
005af339 5011int rearrange_squash(struct repository *r)
c44a4c65
JS
5012{
5013 const char *todo_file = rebase_path_todo();
5014 struct todo_list todo_list = TODO_LIST_INIT;
5015 struct hashmap subject2item;
87805600 5016 int res = 0, rearranged = 0, *next, *tail, i;
c44a4c65 5017 char **subjects;
3cc0287b 5018 struct commit_todo_item commit_todo;
c44a4c65 5019
87805600
RS
5020 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
5021 return -1;
005af339 5022 if (parse_insn_buffer(r, todo_list.buf.buf, &todo_list) < 0) {
c44a4c65
JS
5023 todo_list_release(&todo_list);
5024 return -1;
5025 }
5026
3cc0287b 5027 init_commit_todo_item(&commit_todo);
c44a4c65
JS
5028 /*
5029 * The hashmap maps onelines to the respective todo list index.
5030 *
5031 * If any items need to be rearranged, the next[i] value will indicate
5032 * which item was moved directly after the i'th.
5033 *
5034 * In that case, last[i] will indicate the index of the latest item to
5035 * be moved to appear after the i'th.
5036 */
5037 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
5038 NULL, todo_list.nr);
5039 ALLOC_ARRAY(next, todo_list.nr);
5040 ALLOC_ARRAY(tail, todo_list.nr);
5041 ALLOC_ARRAY(subjects, todo_list.nr);
5042 for (i = 0; i < todo_list.nr; i++) {
5043 struct strbuf buf = STRBUF_INIT;
5044 struct todo_item *item = todo_list.items + i;
5045 const char *commit_buffer, *subject, *p;
5046 size_t subject_len;
5047 int i2 = -1;
5048 struct subject2item_entry *entry;
5049
5050 next[i] = tail[i] = -1;
2f6b1d13 5051 if (!item->commit || item->command == TODO_DROP) {
c44a4c65
JS
5052 subjects[i] = NULL;
5053 continue;
5054 }
5055
5056 if (is_fixup(item->command)) {
5057 todo_list_release(&todo_list);
3cc0287b 5058 clear_commit_todo_item(&commit_todo);
c44a4c65
JS
5059 return error(_("the script was already rearranged."));
5060 }
5061
3cc0287b 5062 *commit_todo_item_at(&commit_todo, item->commit) = item;
c44a4c65
JS
5063
5064 parse_commit(item->commit);
5065 commit_buffer = get_commit_buffer(item->commit, NULL);
5066 find_commit_subject(commit_buffer, &subject);
5067 format_subject(&buf, subject, " ");
5068 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5069 unuse_commit_buffer(item->commit, commit_buffer);
5070 if ((skip_prefix(subject, "fixup! ", &p) ||
5071 skip_prefix(subject, "squash! ", &p))) {
5072 struct commit *commit2;
5073
5074 for (;;) {
5075 while (isspace(*p))
5076 p++;
5077 if (!skip_prefix(p, "fixup! ", &p) &&
5078 !skip_prefix(p, "squash! ", &p))
5079 break;
5080 }
5081
5082 if ((entry = hashmap_get_from_hash(&subject2item,
5083 strhash(p), p)))
5084 /* found by title */
5085 i2 = entry->i;
5086 else if (!strchr(p, ' ') &&
5087 (commit2 =
5088 lookup_commit_reference_by_name(p)) &&
3cc0287b 5089 *commit_todo_item_at(&commit_todo, commit2))
c44a4c65 5090 /* found by commit name */
3cc0287b 5091 i2 = *commit_todo_item_at(&commit_todo, commit2)
c44a4c65
JS
5092 - todo_list.items;
5093 else {
5094 /* copy can be a prefix of the commit subject */
5095 for (i2 = 0; i2 < i; i2++)
5096 if (subjects[i2] &&
5097 starts_with(subjects[i2], p))
5098 break;
5099 if (i2 == i)
5100 i2 = -1;
5101 }
5102 }
5103 if (i2 >= 0) {
5104 rearranged = 1;
5105 todo_list.items[i].command =
5106 starts_with(subject, "fixup!") ?
5107 TODO_FIXUP : TODO_SQUASH;
5108 if (next[i2] < 0)
5109 next[i2] = i;
5110 else
5111 next[tail[i2]] = i;
5112 tail[i2] = i;
5113 } else if (!hashmap_get_from_hash(&subject2item,
5114 strhash(subject), subject)) {
5115 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5116 entry->i = i;
5117 hashmap_entry_init(entry, strhash(entry->subject));
5118 hashmap_put(&subject2item, entry);
5119 }
5120 }
5121
5122 if (rearranged) {
5123 struct strbuf buf = STRBUF_INIT;
5124
5125 for (i = 0; i < todo_list.nr; i++) {
5126 enum todo_command command = todo_list.items[i].command;
5127 int cur = i;
5128
5129 /*
5130 * Initially, all commands are 'pick's. If it is a
5131 * fixup or a squash now, we have rearranged it.
5132 */
5133 if (is_fixup(command))
5134 continue;
5135
5136 while (cur >= 0) {
a01c2a5f
JS
5137 const char *bol =
5138 get_item_line(&todo_list, cur);
5139 const char *eol =
5140 get_item_line(&todo_list, cur + 1);
c44a4c65
JS
5141
5142 /* replace 'pick', by 'fixup' or 'squash' */
5143 command = todo_list.items[cur].command;
5144 if (is_fixup(command)) {
5145 strbuf_addstr(&buf,
5146 todo_command_info[command].str);
5147 bol += strcspn(bol, " \t");
5148 }
5149
5150 strbuf_add(&buf, bol, eol - bol);
5151
5152 cur = next[cur];
5153 }
5154 }
5155
73646bfd 5156 res = rewrite_file(todo_file, buf.buf, buf.len);
c44a4c65
JS
5157 strbuf_release(&buf);
5158 }
5159
5160 free(next);
5161 free(tail);
5162 for (i = 0; i < todo_list.nr; i++)
5163 free(subjects[i]);
5164 free(subjects);
5165 hashmap_free(&subject2item, 1);
5166 todo_list_release(&todo_list);
5167
3cc0287b 5168 clear_commit_todo_item(&commit_todo);
c44a4c65
JS
5169 return res;
5170}