cherry-pick/revert: add scissors line on merge conflict
[git/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")) {
1a2b985f 185 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
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
f29cd862
DL
519enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
520 int use_editor)
521{
522 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
523 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
524 COMMIT_MSG_CLEANUP_SPACE;
525 else if (!strcmp(cleanup_arg, "verbatim"))
526 return COMMIT_MSG_CLEANUP_NONE;
527 else if (!strcmp(cleanup_arg, "whitespace"))
528 return COMMIT_MSG_CLEANUP_SPACE;
529 else if (!strcmp(cleanup_arg, "strip"))
530 return COMMIT_MSG_CLEANUP_ALL;
531 else if (!strcmp(cleanup_arg, "scissors"))
532 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
533 COMMIT_MSG_CLEANUP_SPACE;
534 else
535 die(_("Invalid cleanup mode %s"), cleanup_arg);
536}
537
dc42e9a8
PW
538/*
539 * NB using int rather than enum cleanup_mode to stop clang's
540 * -Wtautological-constant-out-of-range-compare complaining that the comparison
541 * is always true.
542 */
543static const char *describe_cleanup_mode(int cleanup_mode)
544{
545 static const char *modes[] = { "whitespace",
546 "verbatim",
547 "scissors",
548 "strip" };
549
550 if (cleanup_mode < ARRAY_SIZE(modes))
551 return modes[cleanup_mode];
552
553 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
554}
555
f11c9580 556void append_conflicts_hint(struct index_state *istate,
1a2b985f 557 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
75c961b7
JH
558{
559 int i;
560
1a2b985f
DL
561 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
562 strbuf_addch(msgbuf, '\n');
563 wt_status_append_cut_line(msgbuf);
564 strbuf_addch(msgbuf, comment_line_char);
565 }
566
261f315b
JH
567 strbuf_addch(msgbuf, '\n');
568 strbuf_commented_addf(msgbuf, "Conflicts:\n");
f11c9580
NTND
569 for (i = 0; i < istate->cache_nr;) {
570 const struct cache_entry *ce = istate->cache[i++];
75c961b7 571 if (ce_stage(ce)) {
261f315b 572 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
f11c9580
NTND
573 while (i < istate->cache_nr &&
574 !strcmp(ce->name, istate->cache[i]->name))
75c961b7
JH
575 i++;
576 }
577 }
578}
579
f11c9580
NTND
580static int do_recursive_merge(struct repository *r,
581 struct commit *base, struct commit *next,
043a4492 582 const char *base_label, const char *next_label,
48be4c62 583 struct object_id *head, struct strbuf *msgbuf,
043a4492
RR
584 struct replay_opts *opts)
585{
586 struct merge_options o;
587 struct tree *result, *next_tree, *base_tree, *head_tree;
03b86647 588 int clean;
03a4e260 589 char **xopt;
14bca6c6 590 struct lock_file index_lock = LOCK_INIT;
043a4492 591
3a95f31d 592 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
bd588867 593 return -1;
043a4492 594
e1ff0a32 595 repo_read_index(r);
043a4492 596
0d6caa2d 597 init_merge_options(&o, r);
043a4492
RR
598 o.ancestor = base ? base_label : "(empty tree)";
599 o.branch1 = "HEAD";
600 o.branch2 = next ? next_label : "(empty tree)";
62fdb652
JS
601 if (is_rebase_i(opts))
602 o.buffer_output = 2;
9268cf4a 603 o.show_rename_progress = 1;
043a4492
RR
604
605 head_tree = parse_tree_indirect(head);
005af339
NTND
606 next_tree = next ? get_commit_tree(next) : empty_tree(r);
607 base_tree = base ? get_commit_tree(base) : empty_tree(r);
043a4492
RR
608
609 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
610 parse_merge_opt(&o, *xopt);
611
612 clean = merge_trees(&o,
613 head_tree,
614 next_tree, base_tree, &result);
62fdb652
JS
615 if (is_rebase_i(opts) && clean <= 0)
616 fputs(o.obuf.buf, stdout);
548009c0 617 strbuf_release(&o.obuf);
b520abf1 618 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
64816524
619 if (clean < 0) {
620 rollback_lock_file(&index_lock);
f241ff0d 621 return clean;
64816524 622 }
043a4492 623
f11c9580 624 if (write_locked_index(r->index, &index_lock,
61000814 625 COMMIT_LOCK | SKIP_IF_UNCHANGED))
66f5f6dc
ÆAB
626 /*
627 * TRANSLATORS: %s will be "revert", "cherry-pick" or
84583957
JS
628 * "rebase -i".
629 */
c527b55e 630 return error(_("%s: Unable to write new index file"),
c28cbc5e 631 _(action_name(opts)));
043a4492 632
75c961b7 633 if (!clean)
1a2b985f
DL
634 append_conflicts_hint(r->index, msgbuf,
635 opts->default_msg_cleanup);
043a4492
RR
636
637 return !clean;
638}
639
f11c9580 640static struct object_id *get_cache_tree_oid(struct index_state *istate)
ba97aea1 641{
f11c9580
NTND
642 if (!istate->cache_tree)
643 istate->cache_tree = cache_tree();
ba97aea1 644
f11c9580
NTND
645 if (!cache_tree_fully_valid(istate->cache_tree))
646 if (cache_tree_update(istate, 0)) {
ba97aea1
JS
647 error(_("unable to update cache tree"));
648 return NULL;
649 }
650
f11c9580 651 return &istate->cache_tree->oid;
ba97aea1
JS
652}
653
005af339 654static int is_index_unchanged(struct repository *r)
b27cfb0d 655{
ba97aea1 656 struct object_id head_oid, *cache_tree_oid;
b27cfb0d 657 struct commit *head_commit;
005af339 658 struct index_state *istate = r->index;
b27cfb0d 659
49e61479 660 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
aee42e1f 661 return error(_("could not resolve HEAD commit"));
b27cfb0d 662
005af339 663 head_commit = lookup_commit(r, &head_oid);
4b580061
NH
664
665 /*
666 * If head_commit is NULL, check_commit, called from
667 * lookup_commit, would have indicated that head_commit is not
668 * a commit object already. parse_commit() will return failure
669 * without further complaints in such a case. Otherwise, if
670 * the commit is invalid, parse_commit() will complain. So
671 * there is nothing for us to say here. Just return failure.
672 */
673 if (parse_commit(head_commit))
674 return -1;
b27cfb0d 675
f11c9580 676 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
ba97aea1 677 return -1;
b27cfb0d 678
4a7e27e9 679 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
b27cfb0d
NH
680}
681
0473f28a
JS
682static int write_author_script(const char *message)
683{
684 struct strbuf buf = STRBUF_INIT;
685 const char *eol;
686 int res;
687
688 for (;;)
689 if (!*message || starts_with(message, "\n")) {
690missing_author:
691 /* Missing 'author' line? */
692 unlink(rebase_path_author_script());
693 return 0;
694 } else if (skip_prefix(message, "author ", &message))
695 break;
696 else if ((eol = strchr(message, '\n')))
697 message = eol + 1;
698 else
699 goto missing_author;
700
701 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
702 while (*message && *message != '\n' && *message != '\r')
703 if (skip_prefix(message, " <", &message))
704 break;
705 else if (*message != '\'')
706 strbuf_addch(&buf, *(message++));
707 else
4aa5ff94 708 strbuf_addf(&buf, "'\\%c'", *(message++));
0473f28a
JS
709 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
710 while (*message && *message != '\n' && *message != '\r')
711 if (skip_prefix(message, "> ", &message))
712 break;
713 else if (*message != '\'')
714 strbuf_addch(&buf, *(message++));
715 else
4aa5ff94 716 strbuf_addf(&buf, "'\\%c'", *(message++));
0473f28a
JS
717 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
718 while (*message && *message != '\n' && *message != '\r')
719 if (*message != '\'')
720 strbuf_addch(&buf, *(message++));
721 else
4aa5ff94 722 strbuf_addf(&buf, "'\\%c'", *(message++));
0f16c09a 723 strbuf_addch(&buf, '\'');
0473f28a
JS
724 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
725 strbuf_release(&buf);
726 return res;
727}
728
bcd33ec2
PW
729/**
730 * Take a series of KEY='VALUE' lines where VALUE part is
731 * sq-quoted, and append <KEY, VALUE> at the end of the string list
732 */
733static int parse_key_value_squoted(char *buf, struct string_list *list)
734{
735 while (*buf) {
736 struct string_list_item *item;
737 char *np;
738 char *cp = strchr(buf, '=');
739 if (!cp) {
740 np = strchrnul(buf, '\n');
741 return error(_("no key present in '%.*s'"),
742 (int) (np - buf), buf);
743 }
744 np = strchrnul(cp, '\n');
745 *cp++ = '\0';
746 item = string_list_append(list, buf);
747
748 buf = np + (*np == '\n');
749 *np = '\0';
750 cp = sq_dequote(cp);
751 if (!cp)
752 return error(_("unable to dequote value of '%s'"),
753 item->string);
754 item->util = xstrdup(cp);
755 }
756 return 0;
757}
4aa5ff94 758
bcd33ec2
PW
759/**
760 * Reads and parses the state directory's "author-script" file, and sets name,
761 * email and date accordingly.
762 * Returns 0 on success, -1 if the file could not be parsed.
763 *
764 * The author script is of the format:
765 *
766 * GIT_AUTHOR_NAME='$author_name'
767 * GIT_AUTHOR_EMAIL='$author_email'
768 * GIT_AUTHOR_DATE='$author_date'
769 *
770 * where $author_name, $author_email and $author_date are quoted. We are strict
771 * with our parsing, as the file was meant to be eval'd in the old
772 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
773 * from what this function expects, it is better to bail out than to do
774 * something that the user does not expect.
4aa5ff94 775 */
bcd33ec2
PW
776int read_author_script(const char *path, char **name, char **email, char **date,
777 int allow_missing)
4aa5ff94 778{
bcd33ec2
PW
779 struct strbuf buf = STRBUF_INIT;
780 struct string_list kv = STRING_LIST_INIT_DUP;
781 int retval = -1; /* assume failure */
782 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
4aa5ff94 783
bcd33ec2
PW
784 if (strbuf_read_file(&buf, path, 256) <= 0) {
785 strbuf_release(&buf);
786 if (errno == ENOENT && allow_missing)
787 return 0;
788 else
789 return error_errno(_("could not open '%s' for reading"),
790 path);
791 }
792
793 if (parse_key_value_squoted(buf.buf, &kv))
794 goto finish;
795
796 for (i = 0; i < kv.nr; i++) {
797 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
798 if (name_i != -2)
799 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
800 else
801 name_i = i;
802 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
803 if (email_i != -2)
804 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
805 else
806 email_i = i;
807 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
808 if (date_i != -2)
809 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
810 else
811 date_i = i;
812 } else {
813 err = error(_("unknown variable '%s'"),
814 kv.items[i].string);
815 }
816 }
817 if (name_i == -2)
818 error(_("missing 'GIT_AUTHOR_NAME'"));
819 if (email_i == -2)
820 error(_("missing 'GIT_AUTHOR_EMAIL'"));
821 if (date_i == -2)
822 error(_("missing 'GIT_AUTHOR_DATE'"));
823 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
824 goto finish;
825 *name = kv.items[name_i].util;
826 *email = kv.items[email_i].util;
827 *date = kv.items[date_i].util;
828 retval = 0;
829finish:
830 string_list_clear(&kv, !!retval);
831 strbuf_release(&buf);
832 return retval;
4aa5ff94
PW
833}
834
b5a67045 835/*
4d010a75
PW
836 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
837 * file with shell quoting into struct argv_array. Returns -1 on
838 * error, 0 otherwise.
b5a67045 839 */
a2a20b0d 840static int read_env_script(struct argv_array *env)
b5a67045 841{
4d010a75 842 char *name, *email, *date;
b5a67045 843
4d010a75
PW
844 if (read_author_script(rebase_path_author_script(),
845 &name, &email, &date, 0))
a2a20b0d 846 return -1;
b5a67045 847
4d010a75
PW
848 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
849 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
850 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
851 free(name);
852 free(email);
853 free(date);
b5a67045 854
a2a20b0d 855 return 0;
b5a67045
JS
856}
857
356ee465
PW
858static char *get_author(const char *message)
859{
860 size_t len;
861 const char *a;
862
863 a = find_commit_header(message, "author", &len);
864 if (a)
865 return xmemdupz(a, len);
866
867 return NULL;
868}
869
d87d48b2
JS
870/* Read author-script and return an ident line (author <email> timestamp) */
871static const char *read_author_ident(struct strbuf *buf)
872{
67f16e3d 873 struct strbuf out = STRBUF_INIT;
4d010a75 874 char *name, *email, *date;
d87d48b2 875
4d010a75
PW
876 if (read_author_script(rebase_path_author_script(),
877 &name, &email, &date, 0))
d87d48b2
JS
878 return NULL;
879
5522bbac 880 /* validate date since fmt_ident() will die() on bad value */
4d010a75 881 if (parse_date(date, &out)){
5522bbac 882 warning(_("invalid date format '%s' in '%s'"),
4d010a75 883 date, rebase_path_author_script());
5522bbac
ES
884 strbuf_release(&out);
885 return NULL;
886 }
887
888 strbuf_reset(&out);
39ab4d09 889 strbuf_addstr(&out, fmt_ident(name, email, WANT_AUTHOR_IDENT, date, 0));
67f16e3d
ES
890 strbuf_swap(buf, &out);
891 strbuf_release(&out);
4d010a75
PW
892 free(name);
893 free(email);
894 free(date);
d87d48b2
JS
895 return buf->buf;
896}
897
791eb870
JS
898static const char staged_changes_advice[] =
899N_("you have staged changes in your working tree\n"
900"If these changes are meant to be squashed into the previous commit, run:\n"
901"\n"
902" git commit --amend %s\n"
903"\n"
904"If they are meant to go into a new commit, run:\n"
905"\n"
906" git commit %s\n"
907"\n"
908"In both cases, once you're done, continue with:\n"
909"\n"
910" git rebase --continue\n");
911
789b3eff
JS
912#define ALLOW_EMPTY (1<<0)
913#define EDIT_MSG (1<<1)
914#define AMEND_MSG (1<<2)
915#define CLEANUP_MSG (1<<3)
b92ff6e8 916#define VERIFY_MSG (1<<4)
d87d48b2 917#define CREATE_ROOT_COMMIT (1<<5)
789b3eff 918
34bec2c4
AG
919static int run_command_silent_on_success(struct child_process *cmd)
920{
921 struct strbuf buf = STRBUF_INIT;
922 int rc;
923
924 cmd->stdout_to_stderr = 1;
925 rc = pipe_command(cmd,
926 NULL, 0,
927 NULL, 0,
928 &buf, 0);
929
930 if (rc)
931 fputs(buf.buf, stderr);
932 strbuf_release(&buf);
933 return rc;
934}
935
043a4492
RR
936/*
937 * If we are cherry-pick, and if the merge did not result in
938 * hand-editing, we will hit this commit and inherit the original
939 * author date and name.
b5a67045 940 *
043a4492
RR
941 * If we are revert, or if our cherry-pick results in a hand merge,
942 * we had better say that the current user is responsible for that.
b5a67045
JS
943 *
944 * An exception is when run_git_commit() is called during an
945 * interactive rebase: in that case, we will want to retain the
946 * author metadata.
043a4492 947 */
f11c9580
NTND
948static int run_git_commit(struct repository *r,
949 const char *defmsg,
950 struct replay_opts *opts,
789b3eff 951 unsigned int flags)
043a4492 952{
07d968ef 953 struct child_process cmd = CHILD_PROCESS_INIT;
b27cfb0d 954
76fda6eb 955 if ((flags & CREATE_ROOT_COMMIT) && !(flags & AMEND_MSG)) {
d87d48b2 956 struct strbuf msg = STRBUF_INIT, script = STRBUF_INIT;
5dfcfe1e 957 const char *author = NULL;
d87d48b2
JS
958 struct object_id root_commit, *cache_tree_oid;
959 int res = 0;
960
5dfcfe1e
PW
961 if (is_rebase_i(opts)) {
962 author = read_author_ident(&script);
963 if (!author) {
964 strbuf_release(&script);
965 return -1;
966 }
967 }
968
d87d48b2
JS
969 if (!defmsg)
970 BUG("root commit without message");
971
f11c9580 972 if (!(cache_tree_oid = get_cache_tree_oid(r->index)))
d87d48b2
JS
973 res = -1;
974
975 if (!res)
976 res = strbuf_read_file(&msg, defmsg, 0);
977
978 if (res <= 0)
979 res = error_errno(_("could not read '%s'"), defmsg);
980 else
981 res = commit_tree(msg.buf, msg.len, cache_tree_oid,
982 NULL, &root_commit, author,
983 opts->gpg_sign);
984
985 strbuf_release(&msg);
986 strbuf_release(&script);
987 if (!res) {
988 update_ref(NULL, "CHERRY_PICK_HEAD", &root_commit, NULL,
989 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR);
990 res = update_ref(NULL, "HEAD", &root_commit, NULL, 0,
991 UPDATE_REFS_MSG_ON_ERR);
992 }
993 return res < 0 ? error(_("writing root commit")) : 0;
994 }
995
07d968ef
JS
996 cmd.git_cmd = 1;
997
34bec2c4
AG
998 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
999 const char *gpg_opt = gpg_sign_opt_quoted(opts);
a1c75762 1000
34bec2c4
AG
1001 return error(_(staged_changes_advice),
1002 gpg_opt, gpg_opt);
b5a67045
JS
1003 }
1004
07d968ef 1005 argv_array_push(&cmd.args, "commit");
043a4492 1006
b92ff6e8
JS
1007 if (!(flags & VERIFY_MSG))
1008 argv_array_push(&cmd.args, "-n");
789b3eff 1009 if ((flags & AMEND_MSG))
07d968ef 1010 argv_array_push(&cmd.args, "--amend");
3bdd5522 1011 if (opts->gpg_sign)
07d968ef 1012 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
b5a67045 1013 if (defmsg)
07d968ef 1014 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
dc4b5bc3
JS
1015 else if (!(flags & EDIT_MSG))
1016 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
789b3eff 1017 if ((flags & CLEANUP_MSG))
07d968ef 1018 argv_array_push(&cmd.args, "--cleanup=strip");
789b3eff 1019 if ((flags & EDIT_MSG))
07d968ef 1020 argv_array_push(&cmd.args, "-e");
789b3eff 1021 else if (!(flags & CLEANUP_MSG) &&
0009426d 1022 !opts->signoff && !opts->record_origin &&
1a2b985f 1023 !opts->explicit_cleanup)
07d968ef 1024 argv_array_push(&cmd.args, "--cleanup=verbatim");
b27cfb0d 1025
789b3eff 1026 if ((flags & ALLOW_EMPTY))
07d968ef 1027 argv_array_push(&cmd.args, "--allow-empty");
df478b74 1028
a3ec9eaf 1029 if (!(flags & EDIT_MSG))
07d968ef 1030 argv_array_push(&cmd.args, "--allow-empty-message");
4bee9584 1031
34bec2c4
AG
1032 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1033 return run_command_silent_on_success(&cmd);
1034 else
1035 return run_command(&cmd);
b27cfb0d
NH
1036}
1037
d0aaa46f
PW
1038static int rest_is_empty(const struct strbuf *sb, int start)
1039{
1040 int i, eol;
1041 const char *nl;
1042
1043 /* Check if the rest is just whitespace and Signed-off-by's. */
1044 for (i = start; i < sb->len; i++) {
1045 nl = memchr(sb->buf + i, '\n', sb->len - i);
1046 if (nl)
1047 eol = nl - sb->buf;
1048 else
1049 eol = sb->len;
1050
1051 if (strlen(sign_off_header) <= eol - i &&
1052 starts_with(sb->buf + i, sign_off_header)) {
1053 i = eol;
1054 continue;
1055 }
1056 while (i < eol)
1057 if (!isspace(sb->buf[i++]))
1058 return 0;
1059 }
1060
1061 return 1;
1062}
1063
f29cd862
DL
1064void cleanup_message(struct strbuf *msgbuf,
1065 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1066{
1067 if (verbose || /* Truncate the message just before the diff, if any. */
1068 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1069 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1070 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1071 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1072}
1073
d0aaa46f
PW
1074/*
1075 * Find out if the message in the strbuf contains only whitespace and
1076 * Signed-off-by lines.
1077 */
1078int message_is_empty(const struct strbuf *sb,
1079 enum commit_msg_cleanup_mode cleanup_mode)
1080{
1081 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1082 return 0;
1083 return rest_is_empty(sb, 0);
1084}
1085
1086/*
1087 * See if the user edited the message in the editor or left what
1088 * was in the template intact
1089 */
1090int template_untouched(const struct strbuf *sb, const char *template_file,
1091 enum commit_msg_cleanup_mode cleanup_mode)
1092{
1093 struct strbuf tmpl = STRBUF_INIT;
1094 const char *start;
1095
1096 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1097 return 0;
1098
1099 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1100 return 0;
1101
1102 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1103 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1104 start = sb->buf;
1105 strbuf_release(&tmpl);
1106 return rest_is_empty(sb, start - sb->buf);
1107}
1108
0505d604
PW
1109int update_head_with_reflog(const struct commit *old_head,
1110 const struct object_id *new_head,
1111 const char *action, const struct strbuf *msg,
1112 struct strbuf *err)
1113{
1114 struct ref_transaction *transaction;
1115 struct strbuf sb = STRBUF_INIT;
1116 const char *nl;
1117 int ret = 0;
1118
1119 if (action) {
1120 strbuf_addstr(&sb, action);
1121 strbuf_addstr(&sb, ": ");
1122 }
1123
1124 nl = strchr(msg->buf, '\n');
1125 if (nl) {
1126 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1127 } else {
1128 strbuf_addbuf(&sb, msg);
1129 strbuf_addch(&sb, '\n');
1130 }
1131
1132 transaction = ref_transaction_begin(err);
1133 if (!transaction ||
1134 ref_transaction_update(transaction, "HEAD", new_head,
1135 old_head ? &old_head->object.oid : &null_oid,
1136 0, sb.buf, err) ||
1137 ref_transaction_commit(transaction, err)) {
1138 ret = -1;
1139 }
1140 ref_transaction_free(transaction);
1141 strbuf_release(&sb);
1142
1143 return ret;
1144}
1145
a87a6f3c
PW
1146static int run_rewrite_hook(const struct object_id *oldoid,
1147 const struct object_id *newoid)
1148{
1149 struct child_process proc = CHILD_PROCESS_INIT;
1150 const char *argv[3];
1151 int code;
1152 struct strbuf sb = STRBUF_INIT;
1153
1154 argv[0] = find_hook("post-rewrite");
1155 if (!argv[0])
1156 return 0;
1157
1158 argv[1] = "amend";
1159 argv[2] = NULL;
1160
1161 proc.argv = argv;
1162 proc.in = -1;
1163 proc.stdout_to_stderr = 1;
6206286e 1164 proc.trace2_hook_name = "post-rewrite";
a87a6f3c
PW
1165
1166 code = start_command(&proc);
1167 if (code)
1168 return code;
1169 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1170 sigchain_push(SIGPIPE, SIG_IGN);
1171 write_in_full(proc.in, sb.buf, sb.len);
1172 close(proc.in);
1173 strbuf_release(&sb);
1174 sigchain_pop(SIGPIPE);
1175 return finish_command(&proc);
1176}
1177
1d18d758
NTND
1178void commit_post_rewrite(struct repository *r,
1179 const struct commit *old_head,
a87a6f3c
PW
1180 const struct object_id *new_head)
1181{
1182 struct notes_rewrite_cfg *cfg;
1183
1184 cfg = init_copy_notes_for_rewrite("amend");
1185 if (cfg) {
1186 /* we are amending, so old_head is not NULL */
1187 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1d18d758 1188 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
a87a6f3c
PW
1189 }
1190 run_rewrite_hook(&old_head->object.oid, new_head);
1191}
1192
f11c9580
NTND
1193static int run_prepare_commit_msg_hook(struct repository *r,
1194 struct strbuf *msg,
1195 const char *commit)
66618a50
PW
1196{
1197 struct argv_array hook_env = ARGV_ARRAY_INIT;
1198 int ret;
1199 const char *name;
1200
1201 name = git_path_commit_editmsg();
1202 if (write_message(msg->buf, msg->len, name, 0))
1203 return -1;
1204
f11c9580 1205 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", r->index_file);
66618a50
PW
1206 argv_array_push(&hook_env, "GIT_EDITOR=:");
1207 if (commit)
1208 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1209 "commit", commit, NULL);
1210 else
1211 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1212 "message", NULL);
1213 if (ret)
1214 ret = error(_("'prepare-commit-msg' hook failed"));
1215 argv_array_clear(&hook_env);
1216
1217 return ret;
1218}
1219
e47c6caf
PW
1220static const char implicit_ident_advice_noconfig[] =
1221N_("Your name and email address were configured automatically based\n"
1222"on your username and hostname. Please check that they are accurate.\n"
1223"You can suppress this message by setting them explicitly. Run the\n"
1224"following command and follow the instructions in your editor to edit\n"
1225"your configuration file:\n"
1226"\n"
1227" git config --global --edit\n"
1228"\n"
1229"After doing this, you may fix the identity used for this commit with:\n"
1230"\n"
1231" git commit --amend --reset-author\n");
1232
1233static const char implicit_ident_advice_config[] =
1234N_("Your name and email address were configured automatically based\n"
1235"on your username and hostname. Please check that they are accurate.\n"
1236"You can suppress this message by setting them explicitly:\n"
1237"\n"
1238" git config --global user.name \"Your Name\"\n"
1239" git config --global user.email you@example.com\n"
1240"\n"
1241"After doing this, you may fix the identity used for this commit with:\n"
1242"\n"
1243" git commit --amend --reset-author\n");
1244
1245static const char *implicit_ident_advice(void)
1246{
1247 char *user_config = expand_user_path("~/.gitconfig", 0);
1248 char *xdg_config = xdg_config_home("config");
1249 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1250
1251 free(user_config);
1252 free(xdg_config);
1253
1254 if (config_exists)
1255 return _(implicit_ident_advice_config);
1256 else
1257 return _(implicit_ident_advice_noconfig);
1258
1259}
1260
f11c9580
NTND
1261void print_commit_summary(struct repository *r,
1262 const char *prefix,
1263 const struct object_id *oid,
e47c6caf
PW
1264 unsigned int flags)
1265{
1266 struct rev_info rev;
1267 struct commit *commit;
1268 struct strbuf format = STRBUF_INIT;
1269 const char *head;
1270 struct pretty_print_context pctx = {0};
1271 struct strbuf author_ident = STRBUF_INIT;
1272 struct strbuf committer_ident = STRBUF_INIT;
1273
f11c9580 1274 commit = lookup_commit(r, oid);
e47c6caf
PW
1275 if (!commit)
1276 die(_("couldn't look up newly created commit"));
1277 if (parse_commit(commit))
1278 die(_("could not parse newly created commit"));
1279
1280 strbuf_addstr(&format, "format:%h] %s");
1281
1282 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1283 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1284 if (strbuf_cmp(&author_ident, &committer_ident)) {
1285 strbuf_addstr(&format, "\n Author: ");
1286 strbuf_addbuf_percentquote(&format, &author_ident);
1287 }
1288 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1289 struct strbuf date = STRBUF_INIT;
1290
1291 format_commit_message(commit, "%ad", &date, &pctx);
1292 strbuf_addstr(&format, "\n Date: ");
1293 strbuf_addbuf_percentquote(&format, &date);
1294 strbuf_release(&date);
1295 }
1296 if (!committer_ident_sufficiently_given()) {
1297 strbuf_addstr(&format, "\n Committer: ");
1298 strbuf_addbuf_percentquote(&format, &committer_ident);
1299 if (advice_implicit_identity) {
1300 strbuf_addch(&format, '\n');
1301 strbuf_addstr(&format, implicit_ident_advice());
1302 }
1303 }
1304 strbuf_release(&author_ident);
1305 strbuf_release(&committer_ident);
1306
f11c9580 1307 repo_init_revisions(r, &rev, prefix);
e47c6caf
PW
1308 setup_revisions(0, NULL, &rev, NULL);
1309
1310 rev.diff = 1;
1311 rev.diffopt.output_format =
1312 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1313
1314 rev.verbose_header = 1;
1315 rev.show_root_diff = 1;
1316 get_commit_format(format.buf, &rev);
1317 rev.always_show_header = 0;
0f57f731 1318 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
e47c6caf
PW
1319 rev.diffopt.break_opt = 0;
1320 diff_setup_done(&rev.diffopt);
1321
1322 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1323 if (!head)
1324 die_errno(_("unable to resolve HEAD after creating commit"));
1325 if (!strcmp(head, "HEAD"))
1326 head = _("detached HEAD");
1327 else
1328 skip_prefix(head, "refs/heads/", &head);
1329 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1330 _(" (root-commit)") : "");
1331
1332 if (!log_tree_commit(&rev, commit)) {
1333 rev.always_show_header = 1;
1334 rev.use_terminator = 1;
1335 log_tree_commit(&rev, commit);
1336 }
1337
1338 strbuf_release(&format);
1339}
1340
005af339 1341static int parse_head(struct repository *r, struct commit **head)
356ee465
PW
1342{
1343 struct commit *current_head;
1344 struct object_id oid;
1345
1346 if (get_oid("HEAD", &oid)) {
1347 current_head = NULL;
1348 } else {
005af339 1349 current_head = lookup_commit_reference(r, &oid);
356ee465
PW
1350 if (!current_head)
1351 return error(_("could not parse HEAD"));
9001dc2a 1352 if (!oideq(&oid, &current_head->object.oid)) {
356ee465
PW
1353 warning(_("HEAD %s is not a commit!"),
1354 oid_to_hex(&oid));
1355 }
1356 if (parse_commit(current_head))
1357 return error(_("could not parse HEAD commit"));
1358 }
1359 *head = current_head;
1360
1361 return 0;
1362}
1363
1364/*
1365 * Try to commit without forking 'git commit'. In some cases we need
1366 * to run 'git commit' to display an error message
1367 *
1368 * Returns:
1369 * -1 - error unable to commit
1370 * 0 - success
1371 * 1 - run 'git commit'
1372 */
f11c9580
NTND
1373static int try_to_commit(struct repository *r,
1374 struct strbuf *msg, const char *author,
356ee465
PW
1375 struct replay_opts *opts, unsigned int flags,
1376 struct object_id *oid)
1377{
1378 struct object_id tree;
1379 struct commit *current_head;
1380 struct commit_list *parents = NULL;
1381 struct commit_extra_header *extra = NULL;
1382 struct strbuf err = STRBUF_INIT;
66618a50 1383 struct strbuf commit_msg = STRBUF_INIT;
356ee465 1384 char *amend_author = NULL;
66618a50 1385 const char *hook_commit = NULL;
356ee465
PW
1386 enum commit_msg_cleanup_mode cleanup;
1387 int res = 0;
1388
005af339 1389 if (parse_head(r, &current_head))
356ee465
PW
1390 return -1;
1391
1392 if (flags & AMEND_MSG) {
1393 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1394 const char *out_enc = get_commit_output_encoding();
1395 const char *message = logmsg_reencode(current_head, NULL,
1396 out_enc);
1397
1398 if (!msg) {
1399 const char *orig_message = NULL;
1400
1401 find_commit_subject(message, &orig_message);
66618a50 1402 msg = &commit_msg;
356ee465 1403 strbuf_addstr(msg, orig_message);
66618a50 1404 hook_commit = "HEAD";
356ee465
PW
1405 }
1406 author = amend_author = get_author(message);
1407 unuse_commit_buffer(current_head, message);
1408 if (!author) {
1409 res = error(_("unable to parse commit author"));
1410 goto out;
1411 }
1412 parents = copy_commit_list(current_head->parents);
1413 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1414 } else if (current_head) {
1415 commit_list_insert(current_head, &parents);
1416 }
1417
f11c9580 1418 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
356ee465
PW
1419 res = error(_("git write-tree failed to write a tree"));
1420 goto out;
1421 }
1422
4a7e27e9
JK
1423 if (!(flags & ALLOW_EMPTY) && oideq(current_head ?
1424 get_commit_tree_oid(current_head) :
1425 the_hash_algo->empty_tree, &tree)) {
356ee465
PW
1426 res = 1; /* run 'git commit' to display error message */
1427 goto out;
1428 }
1429
66618a50 1430 if (find_hook("prepare-commit-msg")) {
f11c9580 1431 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
66618a50
PW
1432 if (res)
1433 goto out;
1434 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1435 2048) < 0) {
1436 res = error_errno(_("unable to read commit message "
1437 "from '%s'"),
1438 git_path_commit_editmsg());
1439 goto out;
1440 }
1441 msg = &commit_msg;
1442 }
1443
d74f3e58
PW
1444 if (flags & CLEANUP_MSG)
1445 cleanup = COMMIT_MSG_CLEANUP_ALL;
1446 else if ((opts->signoff || opts->record_origin) &&
1447 !opts->explicit_cleanup)
1448 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1449 else
1450 cleanup = opts->default_msg_cleanup;
66618a50
PW
1451
1452 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1453 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
a3ec9eaf 1454 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
66618a50
PW
1455 res = 1; /* run 'git commit' to display error message */
1456 goto out;
1457 }
1458
12f7babd
JS
1459 reset_ident_date();
1460
8be8342b
JH
1461 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1462 oid, author, opts->gpg_sign, extra)) {
356ee465
PW
1463 res = error(_("failed to write commit object"));
1464 goto out;
1465 }
1466
1467 if (update_head_with_reflog(current_head, oid,
1468 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1469 res = error("%s", err.buf);
1470 goto out;
1471 }
1472
1473 if (flags & AMEND_MSG)
1d18d758 1474 commit_post_rewrite(r, current_head, oid);
356ee465
PW
1475
1476out:
1477 free_commit_extra_headers(extra);
1478 strbuf_release(&err);
66618a50 1479 strbuf_release(&commit_msg);
356ee465
PW
1480 free(amend_author);
1481
1482 return res;
1483}
1484
f11c9580
NTND
1485static int do_commit(struct repository *r,
1486 const char *msg_file, const char *author,
356ee465
PW
1487 struct replay_opts *opts, unsigned int flags)
1488{
1489 int res = 1;
1490
d87d48b2
JS
1491 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG) &&
1492 !(flags & CREATE_ROOT_COMMIT)) {
356ee465
PW
1493 struct object_id oid;
1494 struct strbuf sb = STRBUF_INIT;
1495
1496 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1497 return error_errno(_("unable to read commit message "
1498 "from '%s'"),
1499 msg_file);
1500
f11c9580
NTND
1501 res = try_to_commit(r, msg_file ? &sb : NULL,
1502 author, opts, flags, &oid);
356ee465
PW
1503 strbuf_release(&sb);
1504 if (!res) {
f11c9580
NTND
1505 unlink(git_path_cherry_pick_head(r));
1506 unlink(git_path_merge_msg(r));
356ee465 1507 if (!is_rebase_i(opts))
f11c9580 1508 print_commit_summary(r, NULL, &oid,
356ee465
PW
1509 SUMMARY_SHOW_AUTHOR_DATE);
1510 return res;
1511 }
1512 }
1513 if (res == 1)
f11c9580 1514 return run_git_commit(r, msg_file, opts, flags);
356ee465
PW
1515
1516 return res;
1517}
1518
b27cfb0d
NH
1519static int is_original_commit_empty(struct commit *commit)
1520{
092bbcdf 1521 const struct object_id *ptree_oid;
b27cfb0d
NH
1522
1523 if (parse_commit(commit))
aee42e1f 1524 return error(_("could not parse commit %s"),
f2fd0760 1525 oid_to_hex(&commit->object.oid));
b27cfb0d
NH
1526 if (commit->parents) {
1527 struct commit *parent = commit->parents->item;
1528 if (parse_commit(parent))
aee42e1f 1529 return error(_("could not parse parent commit %s"),
f2fd0760 1530 oid_to_hex(&parent->object.oid));
2e27bd77 1531 ptree_oid = get_commit_tree_oid(parent);
b27cfb0d 1532 } else {
eb0ccfd7 1533 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
043a4492 1534 }
043a4492 1535
4a7e27e9 1536 return oideq(ptree_oid, get_commit_tree_oid(commit));
043a4492
RR
1537}
1538
ac2b0e8f
JH
1539/*
1540 * Do we run "git commit" with "--allow-empty"?
1541 */
f11c9580
NTND
1542static int allow_empty(struct repository *r,
1543 struct replay_opts *opts,
1544 struct commit *commit)
ac2b0e8f
JH
1545{
1546 int index_unchanged, empty_commit;
1547
1548 /*
1549 * Three cases:
1550 *
1551 * (1) we do not allow empty at all and error out.
1552 *
1553 * (2) we allow ones that were initially empty, but
1554 * forbid the ones that become empty;
1555 *
1556 * (3) we allow both.
1557 */
1558 if (!opts->allow_empty)
1559 return 0; /* let "git commit" barf as necessary */
1560
005af339 1561 index_unchanged = is_index_unchanged(r);
ac2b0e8f
JH
1562 if (index_unchanged < 0)
1563 return index_unchanged;
1564 if (!index_unchanged)
1565 return 0; /* we do not have to say --allow-empty */
1566
1567 if (opts->keep_redundant_commits)
1568 return 1;
1569
1570 empty_commit = is_original_commit_empty(commit);
1571 if (empty_commit < 0)
1572 return empty_commit;
1573 if (!empty_commit)
1574 return 0;
1575 else
1576 return 1;
1577}
1578
25c43667
JS
1579/*
1580 * Note that ordering matters in this enum. Not only must it match the mapping
1581 * below, it is also divided into several sections that matter. When adding
1582 * new commands, make sure you add it in the right section.
1583 */
004fefa7 1584enum todo_command {
25c43667 1585 /* commands that handle commits */
004fefa7 1586 TODO_PICK = 0,
25c43667 1587 TODO_REVERT,
56dc3ab0 1588 TODO_EDIT,
04efc8b5 1589 TODO_REWORD,
6e98de72
JS
1590 TODO_FIXUP,
1591 TODO_SQUASH,
311af526
JS
1592 /* commands that do something else than handling a single commit */
1593 TODO_EXEC,
71f82465 1594 TODO_BREAK,
9055e401
JS
1595 TODO_LABEL,
1596 TODO_RESET,
4c68e7dd 1597 TODO_MERGE,
25c43667 1598 /* commands that do nothing but are counted for reporting progress */
b3fdd581 1599 TODO_NOOP,
ac191470
JS
1600 TODO_DROP,
1601 /* comments (not counted for reporting progress) */
1602 TODO_COMMENT
004fefa7
JS
1603};
1604
414697a9
JS
1605static struct {
1606 char c;
1607 const char *str;
1608} todo_command_info[] = {
1609 { 'p', "pick" },
1610 { 0, "revert" },
1611 { 'e', "edit" },
04efc8b5 1612 { 'r', "reword" },
414697a9
JS
1613 { 'f', "fixup" },
1614 { 's', "squash" },
1615 { 'x', "exec" },
71f82465 1616 { 'b', "break" },
9055e401
JS
1617 { 'l', "label" },
1618 { 't', "reset" },
4c68e7dd 1619 { 'm', "merge" },
b3fdd581 1620 { 0, "noop" },
ac191470
JS
1621 { 'd', "drop" },
1622 { 0, NULL }
004fefa7
JS
1623};
1624
1625static const char *command_to_string(const enum todo_command command)
1626{
ac191470 1627 if (command < TODO_COMMENT)
414697a9 1628 return todo_command_info[command].str;
02127c63 1629 die(_("unknown command: %d"), command);
004fefa7
JS
1630}
1631
ee5462d6 1632static char command_to_char(const enum todo_command command)
d8ae6c84
LB
1633{
1634 if (command < TODO_COMMENT && todo_command_info[command].c)
1635 return todo_command_info[command].c;
1636 return comment_line_char;
1637}
1638
25c43667
JS
1639static int is_noop(const enum todo_command command)
1640{
b3fdd581 1641 return TODO_NOOP <= command;
25c43667 1642}
004fefa7 1643
6e98de72
JS
1644static int is_fixup(enum todo_command command)
1645{
1646 return command == TODO_FIXUP || command == TODO_SQUASH;
1647}
1648
d87d48b2
JS
1649/* Does this command create a (non-merge) commit? */
1650static int is_pick_or_similar(enum todo_command command)
1651{
1652 switch (command) {
1653 case TODO_PICK:
1654 case TODO_REVERT:
1655 case TODO_EDIT:
1656 case TODO_REWORD:
1657 case TODO_FIXUP:
1658 case TODO_SQUASH:
1659 return 1;
1660 default:
1661 return 0;
1662 }
1663}
1664
005af339
NTND
1665static int update_squash_messages(struct repository *r,
1666 enum todo_command command,
1667 struct commit *commit,
1668 struct replay_opts *opts)
6e98de72
JS
1669{
1670 struct strbuf buf = STRBUF_INIT;
e12a7ef5 1671 int res;
6e98de72
JS
1672 const char *message, *body;
1673
e12a7ef5 1674 if (opts->current_fixup_count > 0) {
6e98de72 1675 struct strbuf header = STRBUF_INIT;
e12a7ef5 1676 char *eol;
6e98de72 1677
e12a7ef5 1678 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
6e98de72
JS
1679 return error(_("could not read '%s'"),
1680 rebase_path_squash_msg());
1681
e12a7ef5
JS
1682 eol = buf.buf[0] != comment_line_char ?
1683 buf.buf : strchrnul(buf.buf, '\n');
6e98de72
JS
1684
1685 strbuf_addf(&header, "%c ", comment_line_char);
e12a7ef5
JS
1686 strbuf_addf(&header, _("This is a combination of %d commits."),
1687 opts->current_fixup_count + 2);
6e98de72
JS
1688 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1689 strbuf_release(&header);
1690 } else {
33d66df3 1691 struct object_id head;
6e98de72
JS
1692 struct commit *head_commit;
1693 const char *head_message, *body;
1694
33d66df3 1695 if (get_oid("HEAD", &head))
6e98de72 1696 return error(_("need a HEAD to fixup"));
005af339 1697 if (!(head_commit = lookup_commit_reference(r, &head)))
6e98de72
JS
1698 return error(_("could not read HEAD"));
1699 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1700 return error(_("could not read HEAD's commit message"));
1701
1702 find_commit_subject(head_message, &body);
1703 if (write_message(body, strlen(body),
1704 rebase_path_fixup_msg(), 0)) {
1705 unuse_commit_buffer(head_commit, head_message);
1706 return error(_("cannot write '%s'"),
1707 rebase_path_fixup_msg());
1708 }
1709
6e98de72 1710 strbuf_addf(&buf, "%c ", comment_line_char);
e12a7ef5 1711 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
6e98de72
JS
1712 strbuf_addf(&buf, "\n%c ", comment_line_char);
1713 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1714 strbuf_addstr(&buf, "\n\n");
1715 strbuf_addstr(&buf, body);
1716
1717 unuse_commit_buffer(head_commit, head_message);
1718 }
1719
1720 if (!(message = get_commit_buffer(commit, NULL)))
1721 return error(_("could not read commit message of %s"),
1722 oid_to_hex(&commit->object.oid));
1723 find_commit_subject(message, &body);
1724
1725 if (command == TODO_SQUASH) {
1726 unlink(rebase_path_fixup_msg());
1727 strbuf_addf(&buf, "\n%c ", comment_line_char);
e12a7ef5 1728 strbuf_addf(&buf, _("This is the commit message #%d:"),
dd2e36eb 1729 ++opts->current_fixup_count + 1);
6e98de72
JS
1730 strbuf_addstr(&buf, "\n\n");
1731 strbuf_addstr(&buf, body);
1732 } else if (command == TODO_FIXUP) {
1733 strbuf_addf(&buf, "\n%c ", comment_line_char);
1734 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
dd2e36eb 1735 ++opts->current_fixup_count + 1);
6e98de72
JS
1736 strbuf_addstr(&buf, "\n\n");
1737 strbuf_add_commented_lines(&buf, body, strlen(body));
1738 } else
1739 return error(_("unknown command: %d"), command);
1740 unuse_commit_buffer(commit, message);
1741
1742 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1743 strbuf_release(&buf);
e12a7ef5
JS
1744
1745 if (!res) {
1746 strbuf_addf(&opts->current_fixups, "%s%s %s",
1747 opts->current_fixups.len ? "\n" : "",
1748 command_to_string(command),
1749 oid_to_hex(&commit->object.oid));
1750 res = write_message(opts->current_fixups.buf,
1751 opts->current_fixups.len,
1752 rebase_path_current_fixups(), 0);
1753 }
1754
6e98de72
JS
1755 return res;
1756}
1757
3b335762
NTND
1758static void flush_rewritten_pending(void)
1759{
25cb8df9 1760 struct strbuf buf = STRBUF_INIT;
092bbcdf 1761 struct object_id newoid;
25cb8df9
JS
1762 FILE *out;
1763
092bbcdf 1764 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1765 !get_oid("HEAD", &newoid) &&
e9d983f1 1766 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
25cb8df9
JS
1767 char *bol = buf.buf, *eol;
1768
1769 while (*bol) {
1770 eol = strchrnul(bol, '\n');
1771 fprintf(out, "%.*s %s\n", (int)(eol - bol),
092bbcdf 1772 bol, oid_to_hex(&newoid));
25cb8df9
JS
1773 if (!*eol)
1774 break;
1775 bol = eol + 1;
1776 }
1777 fclose(out);
1778 unlink(rebase_path_rewritten_pending());
1779 }
1780 strbuf_release(&buf);
1781}
1782
1783static void record_in_rewritten(struct object_id *oid,
3b335762
NTND
1784 enum todo_command next_command)
1785{
e9d983f1 1786 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
25cb8df9
JS
1787
1788 if (!out)
1789 return;
1790
1791 fprintf(out, "%s\n", oid_to_hex(oid));
1792 fclose(out);
1793
1794 if (!is_fixup(next_command))
1795 flush_rewritten_pending();
1796}
1797
f11c9580
NTND
1798static int do_pick_commit(struct repository *r,
1799 enum todo_command command,
1800 struct commit *commit,
1801 struct replay_opts *opts,
1802 int final_fixup)
043a4492 1803{
789b3eff 1804 unsigned int flags = opts->edit ? EDIT_MSG : 0;
f11c9580 1805 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
ace976b2 1806 struct object_id head;
043a4492
RR
1807 struct commit *base, *next, *parent;
1808 const char *base_label, *next_label;
356ee465 1809 char *author = NULL;
d74a4e57 1810 struct commit_message msg = { NULL, NULL, NULL, NULL };
043a4492 1811 struct strbuf msgbuf = STRBUF_INIT;
789b3eff 1812 int res, unborn = 0, allow;
043a4492
RR
1813
1814 if (opts->no_commit) {
1815 /*
1816 * We do not intend to commit immediately. We just want to
1817 * merge the differences in, so let's compute the tree
1818 * that represents the "current" state for merge-recursive
1819 * to work on.
1820 */
f11c9580 1821 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
93b3df6f 1822 return error(_("your index file is unmerged."));
043a4492 1823 } else {
ace976b2 1824 unborn = get_oid("HEAD", &head);
d87d48b2
JS
1825 /* Do we want to generate a root commit? */
1826 if (is_pick_or_similar(command) && opts->have_squash_onto &&
4a7e27e9 1827 oideq(&head, &opts->squash_onto)) {
d87d48b2
JS
1828 if (is_fixup(command))
1829 return error(_("cannot fixup root commit"));
1830 flags |= CREATE_ROOT_COMMIT;
1831 unborn = 1;
1832 } else if (unborn)
eb0ccfd7 1833 oidcpy(&head, the_hash_algo->empty_tree);
ffc00a48 1834 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
02f2f56b 1835 NULL, 0))
e1ff0a32 1836 return error_dirty_index(r, opts);
043a4492 1837 }
f11c9580 1838 discard_index(r->index);
043a4492 1839
637666c8 1840 if (!commit->parents)
043a4492 1841 parent = NULL;
043a4492
RR
1842 else if (commit->parents->next) {
1843 /* Reverting or cherry-picking a merge commit */
1844 int cnt;
1845 struct commit_list *p;
1846
1847 if (!opts->mainline)
93b3df6f 1848 return error(_("commit %s is a merge but no -m option was given."),
f2fd0760 1849 oid_to_hex(&commit->object.oid));
043a4492
RR
1850
1851 for (cnt = 1, p = commit->parents;
1852 cnt != opts->mainline && p;
1853 cnt++)
1854 p = p->next;
1855 if (cnt != opts->mainline || !p)
93b3df6f 1856 return error(_("commit %s does not have parent %d"),
f2fd0760 1857 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492 1858 parent = p->item;
37897bfc
SO
1859 } else if (1 < opts->mainline)
1860 /*
1861 * Non-first parent explicitly specified as mainline for
1862 * non-merge commit
1863 */
1864 return error(_("commit %s does not have parent %d"),
1865 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492
RR
1866 else
1867 parent = commit->parents->item;
1868
bcbb68be
JS
1869 if (get_message(commit, &msg) != 0)
1870 return error(_("cannot get commit message for %s"),
1871 oid_to_hex(&commit->object.oid));
1872
6e98de72 1873 if (opts->allow_ff && !is_fixup(command) &&
4a7e27e9 1874 ((parent && oideq(&parent->object.oid, &head)) ||
bcbb68be
JS
1875 (!parent && unborn))) {
1876 if (is_rebase_i(opts))
1877 write_author_script(msg.message);
f11c9580 1878 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
bcbb68be
JS
1879 opts);
1880 if (res || command != TODO_REWORD)
1881 goto leave;
5f8f9277 1882 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
bcbb68be
JS
1883 msg_file = NULL;
1884 goto fast_forward_edit;
1885 }
043a4492 1886 if (parent && parse_commit(parent) < 0)
004fefa7
JS
1887 /* TRANSLATORS: The first %s will be a "todo" command like
1888 "revert" or "pick", the second %s a SHA1. */
043a4492 1889 return error(_("%s: cannot parse parent commit %s"),
004fefa7
JS
1890 command_to_string(command),
1891 oid_to_hex(&parent->object.oid));
043a4492 1892
043a4492
RR
1893 /*
1894 * "commit" is an existing commit. We would want to apply
1895 * the difference it introduces since its first parent "prev"
1896 * on top of the current HEAD if we are cherry-pick. Or the
1897 * reverse of it if we are revert.
1898 */
1899
004fefa7 1900 if (command == TODO_REVERT) {
043a4492
RR
1901 base = commit;
1902 base_label = msg.label;
1903 next = parent;
1904 next_label = msg.parent_label;
1905 strbuf_addstr(&msgbuf, "Revert \"");
1906 strbuf_addstr(&msgbuf, msg.subject);
1907 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
f2fd0760 1908 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
1909
1910 if (commit->parents && commit->parents->next) {
1911 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
f2fd0760 1912 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
043a4492
RR
1913 }
1914 strbuf_addstr(&msgbuf, ".\n");
1915 } else {
1916 const char *p;
1917
1918 base = parent;
1919 base_label = msg.parent_label;
1920 next = commit;
1921 next_label = msg.label;
1922
23aa5142
JS
1923 /* Append the commit log message to msgbuf. */
1924 if (find_commit_subject(msg.message, &p))
1925 strbuf_addstr(&msgbuf, p);
043a4492
RR
1926
1927 if (opts->record_origin) {
44dc738a 1928 strbuf_complete_line(&msgbuf);
bab4d109 1929 if (!has_conforming_footer(&msgbuf, NULL, 0))
b971e04f 1930 strbuf_addch(&msgbuf, '\n');
cd650a4e 1931 strbuf_addstr(&msgbuf, cherry_picked_prefix);
f2fd0760 1932 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
1933 strbuf_addstr(&msgbuf, ")\n");
1934 }
356ee465
PW
1935 if (!is_fixup(command))
1936 author = get_author(msg.message);
043a4492
RR
1937 }
1938
04efc8b5 1939 if (command == TODO_REWORD)
b92ff6e8 1940 flags |= EDIT_MSG | VERIFY_MSG;
04efc8b5 1941 else if (is_fixup(command)) {
005af339 1942 if (update_squash_messages(r, command, commit, opts))
6e98de72 1943 return -1;
789b3eff 1944 flags |= AMEND_MSG;
6e98de72
JS
1945 if (!final_fixup)
1946 msg_file = rebase_path_squash_msg();
1947 else if (file_exists(rebase_path_fixup_msg())) {
789b3eff 1948 flags |= CLEANUP_MSG;
6e98de72
JS
1949 msg_file = rebase_path_fixup_msg();
1950 } else {
f11c9580 1951 const char *dest = git_path_squash_msg(r);
6e98de72
JS
1952 unlink(dest);
1953 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1954 return error(_("could not rename '%s' to '%s'"),
1955 rebase_path_squash_msg(), dest);
f11c9580 1956 unlink(git_path_merge_msg(r));
6e98de72 1957 msg_file = dest;
789b3eff 1958 flags |= EDIT_MSG;
6e98de72
JS
1959 }
1960 }
1961
a852ec7f 1962 if (opts->signoff && !is_fixup(command))
b34eeea3
PW
1963 append_signoff(&msgbuf, 0, 0);
1964
0473f28a
JS
1965 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1966 res = -1;
1967 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
f11c9580 1968 res = do_recursive_merge(r, base, next, base_label, next_label,
48be4c62 1969 &head, &msgbuf, opts);
f241ff0d 1970 if (res < 0)
19517fb9
SB
1971 goto leave;
1972
75871495 1973 res |= write_message(msgbuf.buf, msgbuf.len,
f11c9580 1974 git_path_merge_msg(r), 0);
043a4492
RR
1975 } else {
1976 struct commit_list *common = NULL;
1977 struct commit_list *remotes = NULL;
1978
75871495 1979 res = write_message(msgbuf.buf, msgbuf.len,
f11c9580 1980 git_path_merge_msg(r), 0);
043a4492
RR
1981
1982 commit_list_insert(base, &common);
1983 commit_list_insert(next, &remotes);
f11c9580 1984 res |= try_merge_command(r, opts->strategy,
03a4e260 1985 opts->xopts_nr, (const char **)opts->xopts,
ace976b2 1986 common, oid_to_hex(&head), remotes);
043a4492
RR
1987 free_commit_list(common);
1988 free_commit_list(remotes);
1989 }
452202c7 1990 strbuf_release(&msgbuf);
043a4492
RR
1991
1992 /*
1993 * If the merge was clean or if it failed due to conflict, we write
1994 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1995 * However, if the merge did not even start, then we don't want to
1996 * write it at all.
1997 */
004fefa7 1998 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
ae077771 1999 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
91774afc 2000 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 2001 res = -1;
004fefa7 2002 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
ae077771 2003 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
91774afc 2004 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 2005 res = -1;
043a4492
RR
2006
2007 if (res) {
004fefa7 2008 error(command == TODO_REVERT
043a4492
RR
2009 ? _("could not revert %s... %s")
2010 : _("could not apply %s... %s"),
39755964 2011 short_commit_name(commit), msg.subject);
005af339 2012 print_advice(r, res == 1, opts);
f11c9580 2013 repo_rerere(r, opts->allow_rerere_auto);
c8d1351d 2014 goto leave;
043a4492
RR
2015 }
2016
f11c9580 2017 allow = allow_empty(r, opts, commit);
706728a3
FC
2018 if (allow < 0) {
2019 res = allow;
2020 goto leave;
789b3eff
JS
2021 } else if (allow)
2022 flags |= ALLOW_EMPTY;
356ee465 2023 if (!opts->no_commit) {
bcbb68be 2024fast_forward_edit:
356ee465 2025 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
f11c9580 2026 res = do_commit(r, msg_file, author, opts, flags);
356ee465
PW
2027 else
2028 res = error(_("unable to parse commit author"));
2029 }
6e98de72
JS
2030
2031 if (!res && final_fixup) {
2032 unlink(rebase_path_fixup_msg());
2033 unlink(rebase_path_squash_msg());
e12a7ef5
JS
2034 unlink(rebase_path_current_fixups());
2035 strbuf_reset(&opts->current_fixups);
2036 opts->current_fixup_count = 0;
6e98de72 2037 }
c8d1351d
FC
2038
2039leave:
d74a4e57 2040 free_message(commit, &msg);
356ee465 2041 free(author);
1e41229d 2042 update_abort_safety_file();
043a4492
RR
2043
2044 return res;
2045}
2046
c3e8618c 2047static int prepare_revs(struct replay_opts *opts)
043a4492 2048{
a73e22e9
MZ
2049 /*
2050 * picking (but not reverting) ranges (but not individual revisions)
2051 * should be done in reverse
2052 */
2053 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
043a4492
RR
2054 opts->revs->reverse ^= 1;
2055
2056 if (prepare_revision_walk(opts->revs))
c3e8618c 2057 return error(_("revision walk setup failed"));
043a4492 2058
c3e8618c 2059 return 0;
043a4492
RR
2060}
2061
f11c9580
NTND
2062static int read_and_refresh_cache(struct repository *r,
2063 struct replay_opts *opts)
043a4492 2064{
14bca6c6 2065 struct lock_file index_lock = LOCK_INIT;
3a95f31d
NTND
2066 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2067 if (repo_read_index(r) < 0) {
49fb937e 2068 rollback_lock_file(&index_lock);
0d9c6dc9 2069 return error(_("git %s: failed to read the index"),
c28cbc5e 2070 _(action_name(opts)));
49fb937e 2071 }
f11c9580 2072 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
61000814 2073 if (index_fd >= 0) {
f11c9580 2074 if (write_locked_index(r->index, &index_lock,
61000814 2075 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
0d9c6dc9 2076 return error(_("git %s: failed to refresh the index"),
c28cbc5e 2077 _(action_name(opts)));
49fb937e 2078 }
043a4492 2079 }
0d9c6dc9 2080 return 0;
043a4492
RR
2081}
2082
4c68e7dd
JS
2083enum todo_item_flags {
2084 TODO_EDIT_MERGE_MSG = 1
2085};
2086
004fefa7
JS
2087struct todo_item {
2088 enum todo_command command;
2089 struct commit *commit;
4c68e7dd 2090 unsigned int flags;
c22f7dfb
JS
2091 const char *arg;
2092 int arg_len;
004fefa7
JS
2093 size_t offset_in_buf;
2094};
2095
2096struct todo_list {
2097 struct strbuf buf;
2098 struct todo_item *items;
2099 int nr, alloc, current;
968492e4 2100 int done_nr, total_nr;
54fd3243 2101 struct stat_data stat;
004fefa7
JS
2102};
2103
2104#define TODO_LIST_INIT { STRBUF_INIT }
2105
2106static void todo_list_release(struct todo_list *todo_list)
043a4492 2107{
004fefa7 2108 strbuf_release(&todo_list->buf);
6a83d902 2109 FREE_AND_NULL(todo_list->items);
004fefa7
JS
2110 todo_list->nr = todo_list->alloc = 0;
2111}
043a4492 2112
004fefa7
JS
2113static struct todo_item *append_new_todo(struct todo_list *todo_list)
2114{
2115 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2116 return todo_list->items + todo_list->nr++;
043a4492
RR
2117}
2118
005af339
NTND
2119static int parse_insn_line(struct repository *r, struct todo_item *item,
2120 const char *bol, char *eol)
043a4492 2121{
1e43ed98 2122 struct object_id commit_oid;
043a4492 2123 char *end_of_object_name;
004fefa7
JS
2124 int i, saved, status, padding;
2125
4c68e7dd
JS
2126 item->flags = 0;
2127
8f8550b3
JS
2128 /* left-trim */
2129 bol += strspn(bol, " \t");
2130
25c43667 2131 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
ac191470 2132 item->command = TODO_COMMENT;
25c43667
JS
2133 item->commit = NULL;
2134 item->arg = bol;
2135 item->arg_len = eol - bol;
2136 return 0;
2137 }
2138
ac191470 2139 for (i = 0; i < TODO_COMMENT; i++)
414697a9
JS
2140 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
2141 item->command = i;
2142 break;
3a4a4cab
JS
2143 } else if ((bol + 1 == eol || bol[1] == ' ') &&
2144 *bol == todo_command_info[i].c) {
414697a9 2145 bol++;
004fefa7
JS
2146 item->command = i;
2147 break;
2148 }
ac191470 2149 if (i >= TODO_COMMENT)
004fefa7 2150 return -1;
043a4492 2151
66afa24f
JS
2152 /* Eat up extra spaces/ tabs before object name */
2153 padding = strspn(bol, " \t");
2154 bol += padding;
2155
71f82465 2156 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
66afa24f
JS
2157 if (bol != eol)
2158 return error(_("%s does not accept arguments: '%s'"),
2159 command_to_string(item->command), bol);
25c43667
JS
2160 item->commit = NULL;
2161 item->arg = bol;
2162 item->arg_len = eol - bol;
2163 return 0;
2164 }
2165
043a4492 2166 if (!padding)
66afa24f
JS
2167 return error(_("missing arguments for %s"),
2168 command_to_string(item->command));
043a4492 2169
9055e401
JS
2170 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2171 item->command == TODO_RESET) {
7dcbb3cb 2172 item->commit = NULL;
311af526
JS
2173 item->arg = bol;
2174 item->arg_len = (int)(eol - bol);
2175 return 0;
2176 }
2177
4c68e7dd
JS
2178 if (item->command == TODO_MERGE) {
2179 if (skip_prefix(bol, "-C", &bol))
2180 bol += strspn(bol, " \t");
2181 else if (skip_prefix(bol, "-c", &bol)) {
2182 bol += strspn(bol, " \t");
2183 item->flags |= TODO_EDIT_MERGE_MSG;
2184 } else {
2185 item->flags |= TODO_EDIT_MERGE_MSG;
2186 item->commit = NULL;
2187 item->arg = bol;
2188 item->arg_len = (int)(eol - bol);
2189 return 0;
2190 }
2191 }
2192
004fefa7 2193 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
043a4492
RR
2194 saved = *end_of_object_name;
2195 *end_of_object_name = '\0';
1e43ed98 2196 status = get_oid(bol, &commit_oid);
043a4492
RR
2197 *end_of_object_name = saved;
2198
c22f7dfb
JS
2199 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
2200 item->arg_len = (int)(eol - item->arg);
2201
043a4492 2202 if (status < 0)
8b637cda
JS
2203 return error(_("could not parse '%.*s'"),
2204 (int)(end_of_object_name - bol), bol);
043a4492 2205
005af339 2206 item->commit = lookup_commit_reference(r, &commit_oid);
004fefa7 2207 return !item->commit;
043a4492
RR
2208}
2209
005af339
NTND
2210static int parse_insn_buffer(struct repository *r, char *buf,
2211 struct todo_list *todo_list)
043a4492 2212{
004fefa7
JS
2213 struct todo_item *item;
2214 char *p = buf, *next_p;
6e98de72 2215 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
043a4492 2216
004fefa7 2217 for (i = 1; *p; i++, p = next_p) {
043a4492 2218 char *eol = strchrnul(p, '\n');
004fefa7
JS
2219
2220 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2221
6307041d
JS
2222 if (p != eol && eol[-1] == '\r')
2223 eol--; /* strip Carriage Return */
2224
004fefa7
JS
2225 item = append_new_todo(todo_list);
2226 item->offset_in_buf = p - todo_list->buf.buf;
005af339 2227 if (parse_insn_line(r, item, p, eol)) {
93b3df6f 2228 res = error(_("invalid line %d: %.*s"),
004fefa7 2229 i, (int)(eol - p), p);
6e98de72 2230 item->command = TODO_NOOP;
004fefa7 2231 }
6e98de72
JS
2232
2233 if (fixup_okay)
2234 ; /* do nothing */
2235 else if (is_fixup(item->command))
2236 return error(_("cannot '%s' without a previous commit"),
2237 command_to_string(item->command));
2238 else if (!is_noop(item->command))
2239 fixup_okay = 1;
043a4492 2240 }
52865279 2241
004fefa7 2242 return res;
043a4492
RR
2243}
2244
968492e4
JS
2245static int count_commands(struct todo_list *todo_list)
2246{
2247 int count = 0, i;
2248
2249 for (i = 0; i < todo_list->nr; i++)
2250 if (todo_list->items[i].command != TODO_COMMENT)
2251 count++;
2252
2253 return count;
2254}
2255
a01c2a5f
JS
2256static int get_item_line_offset(struct todo_list *todo_list, int index)
2257{
2258 return index < todo_list->nr ?
2259 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2260}
2261
2262static const char *get_item_line(struct todo_list *todo_list, int index)
2263{
2264 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2265}
2266
2267static int get_item_line_length(struct todo_list *todo_list, int index)
2268{
2269 return get_item_line_offset(todo_list, index + 1)
2270 - get_item_line_offset(todo_list, index);
2271}
2272
87805600
RS
2273static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2274{
2275 int fd;
2276 ssize_t len;
2277
2278 fd = open(path, O_RDONLY);
2279 if (fd < 0)
2280 return error_errno(_("could not open '%s'"), path);
2281 len = strbuf_read(sb, fd, 0);
2282 close(fd);
2283 if (len < 0)
2284 return error(_("could not read '%s'."), path);
2285 return len;
2286}
2287
005af339
NTND
2288static int read_populate_todo(struct repository *r,
2289 struct todo_list *todo_list,
2290 struct replay_opts *opts)
043a4492 2291{
54fd3243 2292 struct stat st;
c0246501 2293 const char *todo_file = get_todo_path(opts);
87805600 2294 int res;
043a4492 2295
004fefa7 2296 strbuf_reset(&todo_list->buf);
87805600
RS
2297 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2298 return -1;
043a4492 2299
54fd3243
SH
2300 res = stat(todo_file, &st);
2301 if (res)
2302 return error(_("could not stat '%s'"), todo_file);
2303 fill_stat_data(&todo_list->stat, &st);
2304
005af339 2305 res = parse_insn_buffer(r, todo_list->buf.buf, todo_list);
27fdbb96
JS
2306 if (res) {
2307 if (is_rebase_i(opts))
2308 return error(_("please fix this using "
2309 "'git rebase --edit-todo'."));
93b3df6f 2310 return error(_("unusable instruction sheet: '%s'"), todo_file);
27fdbb96 2311 }
2eeaf1b3 2312
52865279
JS
2313 if (!todo_list->nr &&
2314 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2315 return error(_("no commits parsed."));
2316
2eeaf1b3 2317 if (!is_rebase_i(opts)) {
004fefa7
JS
2318 enum todo_command valid =
2319 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2320 int i;
2321
2322 for (i = 0; i < todo_list->nr; i++)
2323 if (valid == todo_list->items[i].command)
2324 continue;
2325 else if (valid == TODO_PICK)
93b3df6f 2326 return error(_("cannot cherry-pick during a revert."));
004fefa7 2327 else
93b3df6f 2328 return error(_("cannot revert during a cherry-pick."));
004fefa7
JS
2329 }
2330
968492e4
JS
2331 if (is_rebase_i(opts)) {
2332 struct todo_list done = TODO_LIST_INIT;
e9d983f1 2333 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
968492e4
JS
2334
2335 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
005af339 2336 !parse_insn_buffer(r, done.buf.buf, &done))
968492e4
JS
2337 todo_list->done_nr = count_commands(&done);
2338 else
2339 todo_list->done_nr = 0;
2340
2341 todo_list->total_nr = todo_list->done_nr
2342 + count_commands(todo_list);
968492e4 2343 todo_list_release(&done);
ef80069a
JS
2344
2345 if (f) {
2346 fprintf(f, "%d\n", todo_list->total_nr);
2347 fclose(f);
2348 }
968492e4
JS
2349 }
2350
0ae42a03 2351 return 0;
043a4492
RR
2352}
2353
03a4e260
JS
2354static int git_config_string_dup(char **dest,
2355 const char *var, const char *value)
2356{
2357 if (!value)
2358 return config_error_nonbool(var);
2359 free(*dest);
2360 *dest = xstrdup(value);
2361 return 0;
2362}
2363
043a4492
RR
2364static int populate_opts_cb(const char *key, const char *value, void *data)
2365{
2366 struct replay_opts *opts = data;
2367 int error_flag = 1;
2368
2369 if (!value)
2370 error_flag = 0;
2371 else if (!strcmp(key, "options.no-commit"))
2372 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2373 else if (!strcmp(key, "options.edit"))
2374 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2375 else if (!strcmp(key, "options.signoff"))
2376 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2377 else if (!strcmp(key, "options.record-origin"))
2378 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2379 else if (!strcmp(key, "options.allow-ff"))
2380 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2381 else if (!strcmp(key, "options.mainline"))
2382 opts->mainline = git_config_int(key, value);
2383 else if (!strcmp(key, "options.strategy"))
03a4e260 2384 git_config_string_dup(&opts->strategy, key, value);
3253553e 2385 else if (!strcmp(key, "options.gpg-sign"))
03a4e260 2386 git_config_string_dup(&opts->gpg_sign, key, value);
043a4492
RR
2387 else if (!strcmp(key, "options.strategy-option")) {
2388 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2389 opts->xopts[opts->xopts_nr++] = xstrdup(value);
8d8cb4b0
PW
2390 } else if (!strcmp(key, "options.allow-rerere-auto"))
2391 opts->allow_rerere_auto =
2392 git_config_bool_or_int(key, value, &error_flag) ?
2393 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
dc42e9a8
PW
2394 else if (!strcmp(key, "options.default-msg-cleanup")) {
2395 opts->explicit_cleanup = 1;
2396 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2397 } else
93b3df6f 2398 return error(_("invalid key: %s"), key);
043a4492
RR
2399
2400 if (!error_flag)
93b3df6f 2401 return error(_("invalid value for %s: %s"), key, value);
043a4492
RR
2402
2403 return 0;
2404}
2405
65850686 2406void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
ca6c6b45
JS
2407{
2408 int i;
65850686 2409 char *strategy_opts_string = raw_opts;
ca6c6b45 2410
0060041d
EN
2411 if (*strategy_opts_string == ' ')
2412 strategy_opts_string++;
65850686 2413
0060041d
EN
2414 opts->xopts_nr = split_cmdline(strategy_opts_string,
2415 (const char ***)&opts->xopts);
ca6c6b45
JS
2416 for (i = 0; i < opts->xopts_nr; i++) {
2417 const char *arg = opts->xopts[i];
2418
2419 skip_prefix(arg, "--", &arg);
2420 opts->xopts[i] = xstrdup(arg);
2421 }
2422}
2423
65850686
AG
2424static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2425{
2426 strbuf_reset(buf);
2427 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2428 return;
2429 opts->strategy = strbuf_detach(buf, NULL);
2430 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2431 return;
2432
2433 parse_strategy_opts(opts, buf->buf);
2434}
2435
5adf9bdc 2436static int read_populate_opts(struct replay_opts *opts)
043a4492 2437{
a1c75762
JS
2438 if (is_rebase_i(opts)) {
2439 struct strbuf buf = STRBUF_INIT;
2440
2441 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2442 if (!starts_with(buf.buf, "-S"))
2443 strbuf_reset(&buf);
2444 else {
2445 free(opts->gpg_sign);
2446 opts->gpg_sign = xstrdup(buf.buf + 2);
2447 }
9b6d7a62
PW
2448 strbuf_reset(&buf);
2449 }
2450
2451 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2452 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2453 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2454 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2455 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2456 strbuf_reset(&buf);
a1c75762 2457 }
a1c75762 2458
556907f1
JS
2459 if (file_exists(rebase_path_verbose()))
2460 opts->verbose = 1;
2461
899b49c4
EN
2462 if (file_exists(rebase_path_quiet()))
2463 opts->quiet = 1;
2464
a852ec7f
PW
2465 if (file_exists(rebase_path_signoff())) {
2466 opts->allow_ff = 0;
2467 opts->signoff = 1;
2468 }
2469
d421afa0
JS
2470 if (file_exists(rebase_path_reschedule_failed_exec()))
2471 opts->reschedule_failed_exec = 1;
2472
ca6c6b45
JS
2473 read_strategy_opts(opts, &buf);
2474 strbuf_release(&buf);
2475
e12a7ef5
JS
2476 if (read_oneliner(&opts->current_fixups,
2477 rebase_path_current_fixups(), 1)) {
2478 const char *p = opts->current_fixups.buf;
2479 opts->current_fixup_count = 1;
2480 while ((p = strchr(p, '\n'))) {
2481 opts->current_fixup_count++;
2482 p++;
2483 }
2484 }
2485
d87d48b2
JS
2486 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2487 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2488 return error(_("unusable squash-onto"));
2489 opts->have_squash_onto = 1;
2490 }
2491
b5a67045 2492 return 0;
a1c75762 2493 }
b5a67045 2494
f932729c 2495 if (!file_exists(git_path_opts_file()))
0d00da7b
JS
2496 return 0;
2497 /*
2498 * The function git_parse_source(), called from git_config_from_file(),
2499 * may die() in case of a syntactically incorrect file. We do not care
2500 * about this case, though, because we wrote that file ourselves, so we
2501 * are pretty certain that it is syntactically correct.
2502 */
5adf9bdc 2503 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
93b3df6f 2504 return error(_("malformed options sheet: '%s'"),
0d00da7b
JS
2505 git_path_opts_file());
2506 return 0;
043a4492
RR
2507}
2508
65850686
AG
2509static void write_strategy_opts(struct replay_opts *opts)
2510{
2511 int i;
2512 struct strbuf buf = STRBUF_INIT;
2513
2514 for (i = 0; i < opts->xopts_nr; ++i)
2515 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2516
2517 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2518 strbuf_release(&buf);
2519}
2520
2521int write_basic_state(struct replay_opts *opts, const char *head_name,
2522 const char *onto, const char *orig_head)
2523{
2524 const char *quiet = getenv("GIT_QUIET");
2525
2526 if (head_name)
2527 write_file(rebase_path_head_name(), "%s\n", head_name);
2528 if (onto)
2529 write_file(rebase_path_onto(), "%s\n", onto);
2530 if (orig_head)
2531 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2532
2533 if (quiet)
2534 write_file(rebase_path_quiet(), "%s\n", quiet);
65850686 2535 if (opts->verbose)
4af51741 2536 write_file(rebase_path_verbose(), "%s", "");
65850686
AG
2537 if (opts->strategy)
2538 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2539 if (opts->xopts_nr > 0)
2540 write_strategy_opts(opts);
2541
2542 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2543 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2544 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2545 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2546
2547 if (opts->gpg_sign)
2548 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2549 if (opts->signoff)
2550 write_file(rebase_path_signoff(), "--signoff\n");
d421afa0
JS
2551 if (opts->reschedule_failed_exec)
2552 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
65850686
AG
2553
2554 return 0;
2555}
2556
004fefa7 2557static int walk_revs_populate_todo(struct todo_list *todo_list,
043a4492
RR
2558 struct replay_opts *opts)
2559{
004fefa7
JS
2560 enum todo_command command = opts->action == REPLAY_PICK ?
2561 TODO_PICK : TODO_REVERT;
414697a9 2562 const char *command_string = todo_command_info[command].str;
043a4492 2563 struct commit *commit;
043a4492 2564
34b0528b
JS
2565 if (prepare_revs(opts))
2566 return -1;
043a4492 2567
004fefa7
JS
2568 while ((commit = get_revision(opts->revs))) {
2569 struct todo_item *item = append_new_todo(todo_list);
2570 const char *commit_buffer = get_commit_buffer(commit, NULL);
2571 const char *subject;
2572 int subject_len;
2573
2574 item->command = command;
2575 item->commit = commit;
c22f7dfb
JS
2576 item->arg = NULL;
2577 item->arg_len = 0;
004fefa7
JS
2578 item->offset_in_buf = todo_list->buf.len;
2579 subject_len = find_commit_subject(commit_buffer, &subject);
2580 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2581 short_commit_name(commit), subject_len, subject);
2582 unuse_commit_buffer(commit, commit_buffer);
2583 }
8530c739
JK
2584
2585 if (!todo_list->nr)
2586 return error(_("empty commit set passed"));
2587
34b0528b 2588 return 0;
043a4492
RR
2589}
2590
2591static int create_seq_dir(void)
2592{
f932729c 2593 if (file_exists(git_path_seq_dir())) {
043a4492
RR
2594 error(_("a cherry-pick or revert is already in progress"));
2595 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2596 return -1;
a70d8f80 2597 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
93b3df6f 2598 return error_errno(_("could not create sequencer directory '%s'"),
f6e82b0d 2599 git_path_seq_dir());
043a4492
RR
2600 return 0;
2601}
2602
311fd397 2603static int save_head(const char *head)
043a4492 2604{
14bca6c6 2605 struct lock_file head_lock = LOCK_INIT;
043a4492
RR
2606 struct strbuf buf = STRBUF_INIT;
2607 int fd;
ed3f9a12 2608 ssize_t written;
043a4492 2609
311fd397 2610 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
350292a1 2611 if (fd < 0)
93b3df6f 2612 return error_errno(_("could not lock HEAD"));
043a4492 2613 strbuf_addf(&buf, "%s\n", head);
ed3f9a12
RS
2614 written = write_in_full(fd, buf.buf, buf.len);
2615 strbuf_release(&buf);
2616 if (written < 0) {
bf5c0571 2617 error_errno(_("could not write to '%s'"), git_path_head_file());
311fd397 2618 rollback_lock_file(&head_lock);
bf5c0571 2619 return -1;
311fd397 2620 }
350292a1
2621 if (commit_lock_file(&head_lock) < 0)
2622 return error(_("failed to finalize '%s'"), git_path_head_file());
311fd397 2623 return 0;
043a4492
RR
2624}
2625
1e41229d
SB
2626static int rollback_is_safe(void)
2627{
2628 struct strbuf sb = STRBUF_INIT;
2629 struct object_id expected_head, actual_head;
2630
2631 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2632 strbuf_trim(&sb);
2633 if (get_oid_hex(sb.buf, &expected_head)) {
2634 strbuf_release(&sb);
2635 die(_("could not parse %s"), git_path_abort_safety_file());
2636 }
2637 strbuf_release(&sb);
2638 }
2639 else if (errno == ENOENT)
2640 oidclr(&expected_head);
2641 else
2642 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2643
2644 if (get_oid("HEAD", &actual_head))
2645 oidclr(&actual_head);
2646
4a7e27e9 2647 return oideq(&actual_head, &expected_head);
1e41229d
SB
2648}
2649
092bbcdf 2650static int reset_for_rollback(const struct object_id *oid)
043a4492
RR
2651{
2652 const char *argv[4]; /* reset --merge <arg> + NULL */
1e41229d 2653
043a4492
RR
2654 argv[0] = "reset";
2655 argv[1] = "--merge";
092bbcdf 2656 argv[2] = oid_to_hex(oid);
043a4492
RR
2657 argv[3] = NULL;
2658 return run_command_v_opt(argv, RUN_GIT_CMD);
2659}
2660
005af339 2661static int rollback_single_pick(struct repository *r)
043a4492 2662{
092bbcdf 2663 struct object_id head_oid;
043a4492 2664
005af339
NTND
2665 if (!file_exists(git_path_cherry_pick_head(r)) &&
2666 !file_exists(git_path_revert_head(r)))
043a4492 2667 return error(_("no cherry-pick or revert in progress"));
34c290a6 2668 if (read_ref_full("HEAD", 0, &head_oid, NULL))
043a4492 2669 return error(_("cannot resolve HEAD"));
092bbcdf 2670 if (is_null_oid(&head_oid))
043a4492 2671 return error(_("cannot abort from a branch yet to be born"));
092bbcdf 2672 return reset_for_rollback(&head_oid);
043a4492
RR
2673}
2674
005af339 2675int sequencer_rollback(struct repository *r, struct replay_opts *opts)
043a4492 2676{
043a4492 2677 FILE *f;
092bbcdf 2678 struct object_id oid;
043a4492 2679 struct strbuf buf = STRBUF_INIT;
092bbcdf 2680 const char *p;
043a4492 2681
f932729c 2682 f = fopen(git_path_head_file(), "r");
043a4492
RR
2683 if (!f && errno == ENOENT) {
2684 /*
2685 * There is no multiple-cherry-pick in progress.
2686 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2687 * a single-cherry-pick in progress, abort that.
2688 */
005af339 2689 return rollback_single_pick(r);
043a4492
RR
2690 }
2691 if (!f)
f7ed1953 2692 return error_errno(_("cannot open '%s'"), git_path_head_file());
8f309aeb 2693 if (strbuf_getline_lf(&buf, f)) {
f7ed1953 2694 error(_("cannot read '%s': %s"), git_path_head_file(),
f932729c 2695 ferror(f) ? strerror(errno) : _("unexpected end of file"));
043a4492
RR
2696 fclose(f);
2697 goto fail;
2698 }
2699 fclose(f);
092bbcdf 2700 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
043a4492 2701 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
f932729c 2702 git_path_head_file());
043a4492
RR
2703 goto fail;
2704 }
092bbcdf 2705 if (is_null_oid(&oid)) {
0f974e21
MG
2706 error(_("cannot abort from a branch yet to be born"));
2707 goto fail;
2708 }
1e41229d
SB
2709
2710 if (!rollback_is_safe()) {
2711 /* Do not error, just do not rollback */
2712 warning(_("You seem to have moved HEAD. "
2713 "Not rewinding, check your HEAD!"));
2714 } else
092bbcdf 2715 if (reset_for_rollback(&oid))
043a4492 2716 goto fail;
043a4492 2717 strbuf_release(&buf);
2863584f 2718 return sequencer_remove_state(opts);
043a4492
RR
2719fail:
2720 strbuf_release(&buf);
2721 return -1;
2722}
2723
004fefa7 2724static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
043a4492 2725{
14bca6c6 2726 struct lock_file todo_lock = LOCK_INIT;
004fefa7
JS
2727 const char *todo_path = get_todo_path(opts);
2728 int next = todo_list->current, offset, fd;
043a4492 2729
84583957
JS
2730 /*
2731 * rebase -i writes "git-rebase-todo" without the currently executing
2732 * command, appending it to "done" instead.
2733 */
2734 if (is_rebase_i(opts))
2735 next++;
2736
004fefa7 2737 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
221675de 2738 if (fd < 0)
93b3df6f 2739 return error_errno(_("could not lock '%s'"), todo_path);
a01c2a5f 2740 offset = get_item_line_offset(todo_list, next);
004fefa7
JS
2741 if (write_in_full(fd, todo_list->buf.buf + offset,
2742 todo_list->buf.len - offset) < 0)
93b3df6f 2743 return error_errno(_("could not write to '%s'"), todo_path);
004fefa7 2744 if (commit_lock_file(&todo_lock) < 0)
350292a1 2745 return error(_("failed to finalize '%s'"), todo_path);
1df6df0c 2746
a01c2a5f
JS
2747 if (is_rebase_i(opts) && next > 0) {
2748 const char *done = rebase_path_done();
2749 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2750 int ret = 0;
1df6df0c 2751
a01c2a5f
JS
2752 if (fd < 0)
2753 return 0;
2754 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2755 get_item_line_length(todo_list, next - 1))
2756 < 0)
2757 ret = error_errno(_("could not write to '%s'"), done);
2758 if (close(fd) < 0)
2759 ret = error_errno(_("failed to finalize '%s'"), done);
2760 return ret;
1df6df0c 2761 }
221675de 2762 return 0;
043a4492
RR
2763}
2764
88d5a271 2765static int save_opts(struct replay_opts *opts)
043a4492 2766{
f932729c 2767 const char *opts_file = git_path_opts_file();
88d5a271 2768 int res = 0;
043a4492
RR
2769
2770 if (opts->no_commit)
88d5a271 2771 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
043a4492 2772 if (opts->edit)
88d5a271 2773 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
043a4492 2774 if (opts->signoff)
88d5a271 2775 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
043a4492 2776 if (opts->record_origin)
88d5a271 2777 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
043a4492 2778 if (opts->allow_ff)
88d5a271 2779 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
043a4492
RR
2780 if (opts->mainline) {
2781 struct strbuf buf = STRBUF_INIT;
2782 strbuf_addf(&buf, "%d", opts->mainline);
88d5a271 2783 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
043a4492
RR
2784 strbuf_release(&buf);
2785 }
2786 if (opts->strategy)
88d5a271 2787 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
3253553e 2788 if (opts->gpg_sign)
88d5a271 2789 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
043a4492
RR
2790 if (opts->xopts) {
2791 int i;
2792 for (i = 0; i < opts->xopts_nr; i++)
88d5a271 2793 res |= git_config_set_multivar_in_file_gently(opts_file,
043a4492
RR
2794 "options.strategy-option",
2795 opts->xopts[i], "^$", 0);
2796 }
8d8cb4b0
PW
2797 if (opts->allow_rerere_auto)
2798 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2799 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2800 "true" : "false");
dc42e9a8
PW
2801
2802 if (opts->explicit_cleanup)
2803 res |= git_config_set_in_file_gently(opts_file,
2804 "options.default-msg-cleanup",
2805 describe_cleanup_mode(opts->default_msg_cleanup));
88d5a271 2806 return res;
043a4492
RR
2807}
2808
f11c9580
NTND
2809static int make_patch(struct repository *r,
2810 struct commit *commit,
2811 struct replay_opts *opts)
56dc3ab0
JS
2812{
2813 struct strbuf buf = STRBUF_INIT;
2814 struct rev_info log_tree_opt;
2815 const char *subject, *p;
2816 int res = 0;
2817
2818 p = short_commit_name(commit);
2819 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2820 return -1;
fbd7a232
NTND
2821 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2822 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2823 res |= error(_("could not update %s"), "REBASE_HEAD");
56dc3ab0
JS
2824
2825 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2826 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 2827 repo_init_revisions(r, &log_tree_opt, NULL);
56dc3ab0
JS
2828 log_tree_opt.abbrev = 0;
2829 log_tree_opt.diff = 1;
2830 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2831 log_tree_opt.disable_stdin = 1;
2832 log_tree_opt.no_commit_id = 1;
2833 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2834 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2835 if (!log_tree_opt.diffopt.file)
2836 res |= error_errno(_("could not open '%s'"), buf.buf);
2837 else {
2838 res |= log_tree_commit(&log_tree_opt, commit);
2839 fclose(log_tree_opt.diffopt.file);
2840 }
2841 strbuf_reset(&buf);
2842
2843 strbuf_addf(&buf, "%s/message", get_dir(opts));
2844 if (!file_exists(buf.buf)) {
2845 const char *commit_buffer = get_commit_buffer(commit, NULL);
2846 find_commit_subject(commit_buffer, &subject);
2847 res |= write_message(subject, strlen(subject), buf.buf, 1);
2848 unuse_commit_buffer(commit, commit_buffer);
2849 }
2850 strbuf_release(&buf);
2851
2852 return res;
2853}
2854
2855static int intend_to_amend(void)
2856{
092bbcdf 2857 struct object_id head;
56dc3ab0
JS
2858 char *p;
2859
092bbcdf 2860 if (get_oid("HEAD", &head))
56dc3ab0
JS
2861 return error(_("cannot read HEAD"));
2862
092bbcdf 2863 p = oid_to_hex(&head);
56dc3ab0
JS
2864 return write_message(p, strlen(p), rebase_path_amend(), 1);
2865}
2866
f11c9580
NTND
2867static int error_with_patch(struct repository *r,
2868 struct commit *commit,
2869 const char *subject, int subject_len,
2870 struct replay_opts *opts,
2871 int exit_code, int to_amend)
56dc3ab0 2872{
bc9238bb 2873 if (commit) {
f11c9580 2874 if (make_patch(r, commit, opts))
bc9238bb 2875 return -1;
5a5c5e95 2876 } else if (copy_file(rebase_path_message(),
f11c9580 2877 git_path_merge_msg(r), 0666))
bc9238bb 2878 return error(_("unable to copy '%s' to '%s'"),
f11c9580 2879 git_path_merge_msg(r), rebase_path_message());
56dc3ab0
JS
2880
2881 if (to_amend) {
2882 if (intend_to_amend())
2883 return -1;
2884
02127c63
NTND
2885 fprintf(stderr,
2886 _("You can amend the commit now, with\n"
2887 "\n"
2888 " git commit --amend %s\n"
2889 "\n"
2890 "Once you are satisfied with your changes, run\n"
2891 "\n"
2892 " git rebase --continue\n"),
2893 gpg_sign_opt_quoted(opts));
bc9238bb
PW
2894 } else if (exit_code) {
2895 if (commit)
5a5c5e95
JH
2896 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
2897 short_commit_name(commit), subject_len, subject);
bc9238bb
PW
2898 else
2899 /*
2900 * We don't have the hash of the parent so
2901 * just print the line from the todo file.
2902 */
5a5c5e95
JH
2903 fprintf_ln(stderr, _("Could not merge %.*s"),
2904 subject_len, subject);
bc9238bb 2905 }
56dc3ab0
JS
2906
2907 return exit_code;
2908}
2909
f11c9580
NTND
2910static int error_failed_squash(struct repository *r,
2911 struct commit *commit,
2912 struct replay_opts *opts,
2913 int subject_len,
2914 const char *subject)
6e98de72 2915{
e12a7ef5
JS
2916 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
2917 return error(_("could not copy '%s' to '%s'"),
6e98de72 2918 rebase_path_squash_msg(), rebase_path_message());
f11c9580
NTND
2919 unlink(git_path_merge_msg(r));
2920 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
6e98de72 2921 return error(_("could not copy '%s' to '%s'"),
102de880 2922 rebase_path_message(),
f11c9580
NTND
2923 git_path_merge_msg(r));
2924 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
6e98de72
JS
2925}
2926
f11c9580 2927static int do_exec(struct repository *r, const char *command_line)
311af526 2928{
09d7b6c6 2929 struct argv_array child_env = ARGV_ARRAY_INIT;
311af526
JS
2930 const char *child_argv[] = { NULL, NULL };
2931 int dirty, status;
2932
2933 fprintf(stderr, "Executing: %s\n", command_line);
2934 child_argv[0] = command_line;
09d7b6c6 2935 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
ab5e67d7 2936 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
2937 absolute_path(get_git_work_tree()));
09d7b6c6
JK
2938 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2939 child_env.argv);
311af526
JS
2940
2941 /* force re-reading of the cache */
e1ff0a32 2942 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
311af526
JS
2943 return error(_("could not read index"));
2944
f11c9580 2945 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
311af526
JS
2946
2947 if (status) {
2948 warning(_("execution failed: %s\n%s"
2949 "You can fix the problem, and then run\n"
2950 "\n"
2951 " git rebase --continue\n"
2952 "\n"),
2953 command_line,
2954 dirty ? N_("and made changes to the index and/or the "
2955 "working tree\n") : "");
2956 if (status == 127)
2957 /* command not found */
2958 status = 1;
2959 } else if (dirty) {
2960 warning(_("execution succeeded: %s\nbut "
2961 "left changes to the index and/or the working tree\n"
2962 "Commit or stash your changes, and then run\n"
2963 "\n"
2964 " git rebase --continue\n"
2965 "\n"), command_line);
2966 status = 1;
2967 }
2968
09d7b6c6
JK
2969 argv_array_clear(&child_env);
2970
311af526
JS
2971 return status;
2972}
2973
9055e401
JS
2974static int safe_append(const char *filename, const char *fmt, ...)
2975{
2976 va_list ap;
2977 struct lock_file lock = LOCK_INIT;
2978 int fd = hold_lock_file_for_update(&lock, filename,
2979 LOCK_REPORT_ON_ERROR);
2980 struct strbuf buf = STRBUF_INIT;
2981
2982 if (fd < 0)
2983 return -1;
2984
2985 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2986 error_errno(_("could not read '%s'"), filename);
2987 rollback_lock_file(&lock);
2988 return -1;
2989 }
2990 strbuf_complete(&buf, '\n');
2991 va_start(ap, fmt);
2992 strbuf_vaddf(&buf, fmt, ap);
2993 va_end(ap);
2994
2995 if (write_in_full(fd, buf.buf, buf.len) < 0) {
2996 error_errno(_("could not write to '%s'"), filename);
2997 strbuf_release(&buf);
2998 rollback_lock_file(&lock);
2999 return -1;
3000 }
3001 if (commit_lock_file(&lock) < 0) {
3002 strbuf_release(&buf);
3003 rollback_lock_file(&lock);
3004 return error(_("failed to finalize '%s'"), filename);
3005 }
3006
3007 strbuf_release(&buf);
3008 return 0;
3009}
3010
f11c9580 3011static int do_label(struct repository *r, const char *name, int len)
9055e401 3012{
f11c9580 3013 struct ref_store *refs = get_main_ref_store(r);
9055e401
JS
3014 struct ref_transaction *transaction;
3015 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3016 struct strbuf msg = STRBUF_INIT;
3017 int ret = 0;
3018 struct object_id head_oid;
3019
3020 if (len == 1 && *name == '#')
02127c63 3021 return error(_("illegal label name: '%.*s'"), len, name);
9055e401
JS
3022
3023 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3024 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
3025
3026 transaction = ref_store_transaction_begin(refs, &err);
3027 if (!transaction) {
3028 error("%s", err.buf);
3029 ret = -1;
3030 } else if (get_oid("HEAD", &head_oid)) {
3031 error(_("could not read HEAD"));
3032 ret = -1;
3033 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3034 NULL, 0, msg.buf, &err) < 0 ||
3035 ref_transaction_commit(transaction, &err)) {
3036 error("%s", err.buf);
3037 ret = -1;
3038 }
3039 ref_transaction_free(transaction);
3040 strbuf_release(&err);
3041 strbuf_release(&msg);
3042
3043 if (!ret)
3044 ret = safe_append(rebase_path_refs_to_delete(),
3045 "%s\n", ref_name.buf);
3046 strbuf_release(&ref_name);
3047
3048 return ret;
3049}
3050
3051static const char *reflog_message(struct replay_opts *opts,
3052 const char *sub_action, const char *fmt, ...);
3053
f11c9580
NTND
3054static int do_reset(struct repository *r,
3055 const char *name, int len,
3056 struct replay_opts *opts)
9055e401
JS
3057{
3058 struct strbuf ref_name = STRBUF_INIT;
3059 struct object_id oid;
3060 struct lock_file lock = LOCK_INIT;
3061 struct tree_desc desc;
3062 struct tree *tree;
3063 struct unpack_trees_options unpack_tree_opts;
71571cd7 3064 int ret = 0;
9055e401 3065
3a95f31d 3066 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
9055e401
JS
3067 return -1;
3068
ebddf393
JS
3069 if (len == 10 && !strncmp("[new root]", name, len)) {
3070 if (!opts->have_squash_onto) {
3071 const char *hex;
3072 if (commit_tree("", 0, the_hash_algo->empty_tree,
3073 NULL, &opts->squash_onto,
3074 NULL, NULL))
3075 return error(_("writing fake root commit"));
3076 opts->have_squash_onto = 1;
3077 hex = oid_to_hex(&opts->squash_onto);
3078 if (write_message(hex, strlen(hex),
3079 rebase_path_squash_onto(), 0))
3080 return error(_("writing squash-onto"));
3081 }
3082 oidcpy(&oid, &opts->squash_onto);
3083 } else {
71571cd7
3084 int i;
3085
ebddf393
JS
3086 /* Determine the length of the label */
3087 for (i = 0; i < len; i++)
3088 if (isspace(name[i]))
71571cd7
3089 break;
3090 len = i;
ebddf393
JS
3091
3092 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3093 if (get_oid(ref_name.buf, &oid) &&
3094 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3095 error(_("could not read '%s'"), ref_name.buf);
3096 rollback_lock_file(&lock);
3097 strbuf_release(&ref_name);
3098 return -1;
3099 }
9055e401
JS
3100 }
3101
3102 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3103 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3104 unpack_tree_opts.head_idx = 1;
f11c9580
NTND
3105 unpack_tree_opts.src_index = r->index;
3106 unpack_tree_opts.dst_index = r->index;
9055e401
JS
3107 unpack_tree_opts.fn = oneway_merge;
3108 unpack_tree_opts.merge = 1;
3109 unpack_tree_opts.update = 1;
3110
e1ff0a32 3111 if (repo_read_index_unmerged(r)) {
9055e401
JS
3112 rollback_lock_file(&lock);
3113 strbuf_release(&ref_name);
3114 return error_resolve_conflict(_(action_name(opts)));
3115 }
3116
3117 if (!fill_tree_descriptor(&desc, &oid)) {
3118 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3119 rollback_lock_file(&lock);
3120 free((void *)desc.buffer);
3121 strbuf_release(&ref_name);
3122 return -1;
3123 }
3124
3125 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3126 rollback_lock_file(&lock);
3127 free((void *)desc.buffer);
3128 strbuf_release(&ref_name);
3129 return -1;
3130 }
3131
3132 tree = parse_tree_indirect(&oid);
c207e9e1 3133 prime_cache_tree(r, r->index, tree);
9055e401 3134
f11c9580 3135 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
9055e401
JS
3136 ret = error(_("could not write index"));
3137 free((void *)desc.buffer);
3138
3139 if (!ret)
3140 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3141 len, name), "HEAD", &oid,
3142 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3143
3144 strbuf_release(&ref_name);
3145 return ret;
3146}
3147
2b6ad0f4
JS
3148static struct commit *lookup_label(const char *label, int len,
3149 struct strbuf *buf)
3150{
3151 struct commit *commit;
3152
3153 strbuf_reset(buf);
3154 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3155 commit = lookup_commit_reference_by_name(buf->buf);
3156 if (!commit) {
3157 /* fall back to non-rewritten ref or commit */
3158 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3159 commit = lookup_commit_reference_by_name(buf->buf);
3160 }
3161
3162 if (!commit)
3163 error(_("could not resolve '%s'"), buf->buf);
3164
3165 return commit;
3166}
3167
f11c9580
NTND
3168static int do_merge(struct repository *r,
3169 struct commit *commit,
3170 const char *arg, int arg_len,
4c68e7dd
JS
3171 int flags, struct replay_opts *opts)
3172{
3173 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3174 EDIT_MSG | VERIFY_MSG : 0;
3175 struct strbuf ref_name = STRBUF_INIT;
3176 struct commit *head_commit, *merge_commit, *i;
3177 struct commit_list *bases, *j, *reversed = NULL;
2b6ad0f4 3178 struct commit_list *to_merge = NULL, **tail = &to_merge;
4c68e7dd 3179 struct merge_options o;
2b6ad0f4 3180 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4c68e7dd
JS
3181 static struct lock_file lock;
3182 const char *p;
3183
3a95f31d 3184 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4c68e7dd
JS
3185 ret = -1;
3186 goto leave_merge;
3187 }
3188
3189 head_commit = lookup_commit_reference_by_name("HEAD");
3190 if (!head_commit) {
3191 ret = error(_("cannot merge without a current revision"));
3192 goto leave_merge;
3193 }
3194
2b6ad0f4
JS
3195 /*
3196 * For octopus merges, the arg starts with the list of revisions to be
3197 * merged. The list is optionally followed by '#' and the oneline.
3198 */
3199 merge_arg_len = oneline_offset = arg_len;
3200 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3201 if (!*p)
3202 break;
3203 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3204 p += 1 + strspn(p + 1, " \t\n");
3205 oneline_offset = p - arg;
3206 break;
3207 }
3208 k = strcspn(p, " \t\n");
3209 if (!k)
3210 continue;
3211 merge_commit = lookup_label(p, k, &ref_name);
3212 if (!merge_commit) {
3213 ret = error(_("unable to parse '%.*s'"), k, p);
3214 goto leave_merge;
3215 }
3216 tail = &commit_list_insert(merge_commit, tail)->next;
3217 p += k;
3218 merge_arg_len = p - arg;
4c68e7dd
JS
3219 }
3220
2b6ad0f4
JS
3221 if (!to_merge) {
3222 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4c68e7dd
JS
3223 goto leave_merge;
3224 }
3225
9c85a1c2 3226 if (opts->have_squash_onto &&
4a7e27e9 3227 oideq(&head_commit->object.oid, &opts->squash_onto)) {
9c85a1c2
JS
3228 /*
3229 * When the user tells us to "merge" something into a
3230 * "[new root]", let's simply fast-forward to the merge head.
3231 */
3232 rollback_lock_file(&lock);
2b6ad0f4
JS
3233 if (to_merge->next)
3234 ret = error(_("octopus merge cannot be executed on "
3235 "top of a [new root]"));
3236 else
f11c9580 3237 ret = fast_forward_to(r, &to_merge->item->object.oid,
2b6ad0f4
JS
3238 &head_commit->object.oid, 0,
3239 opts);
9c85a1c2
JS
3240 goto leave_merge;
3241 }
3242
4c68e7dd
JS
3243 if (commit) {
3244 const char *message = get_commit_buffer(commit, NULL);
3245 const char *body;
3246 int len;
3247
3248 if (!message) {
3249 ret = error(_("could not get commit message of '%s'"),
3250 oid_to_hex(&commit->object.oid));
3251 goto leave_merge;
3252 }
3253 write_author_script(message);
3254 find_commit_subject(message, &body);
3255 len = strlen(body);
f11c9580 3256 ret = write_message(body, len, git_path_merge_msg(r), 0);
4c68e7dd
JS
3257 unuse_commit_buffer(commit, message);
3258 if (ret) {
3259 error_errno(_("could not write '%s'"),
f11c9580 3260 git_path_merge_msg(r));
4c68e7dd
JS
3261 goto leave_merge;
3262 }
3263 } else {
3264 struct strbuf buf = STRBUF_INIT;
3265 int len;
3266
3267 strbuf_addf(&buf, "author %s", git_author_info(0));
3268 write_author_script(buf.buf);
3269 strbuf_reset(&buf);
3270
3271 if (oneline_offset < arg_len) {
3272 p = arg + oneline_offset;
3273 len = arg_len - oneline_offset;
3274 } else {
2b6ad0f4
JS
3275 strbuf_addf(&buf, "Merge %s '%.*s'",
3276 to_merge->next ? "branches" : "branch",
4c68e7dd
JS
3277 merge_arg_len, arg);
3278 p = buf.buf;
3279 len = buf.len;
3280 }
3281
f11c9580 3282 ret = write_message(p, len, git_path_merge_msg(r), 0);
4c68e7dd
JS
3283 strbuf_release(&buf);
3284 if (ret) {
3285 error_errno(_("could not write '%s'"),
f11c9580 3286 git_path_merge_msg(r));
4c68e7dd
JS
3287 goto leave_merge;
3288 }
3289 }
3290
d1e8b011
JS
3291 /*
3292 * If HEAD is not identical to the first parent of the original merge
3293 * commit, we cannot fast-forward.
3294 */
3295 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4a7e27e9
JK
3296 oideq(&commit->parents->item->object.oid,
3297 &head_commit->object.oid);
d1e8b011
JS
3298
3299 /*
2b6ad0f4 3300 * If any merge head is different from the original one, we cannot
d1e8b011
JS
3301 * fast-forward.
3302 */
3303 if (can_fast_forward) {
2b6ad0f4 3304 struct commit_list *p = commit->parents->next;
d1e8b011 3305
2b6ad0f4 3306 for (j = to_merge; j && p; j = j->next, p = p->next)
9001dc2a 3307 if (!oideq(&j->item->object.oid,
2b6ad0f4
JS
3308 &p->item->object.oid)) {
3309 can_fast_forward = 0;
3310 break;
3311 }
3312 /*
3313 * If the number of merge heads differs from the original merge
3314 * commit, we cannot fast-forward.
3315 */
3316 if (j || p)
d1e8b011
JS
3317 can_fast_forward = 0;
3318 }
3319
2b6ad0f4 3320 if (can_fast_forward) {
d1e8b011 3321 rollback_lock_file(&lock);
f11c9580 3322 ret = fast_forward_to(r, &commit->object.oid,
d1e8b011
JS
3323 &head_commit->object.oid, 0, opts);
3324 goto leave_merge;
3325 }
3326
2b6ad0f4
JS
3327 if (to_merge->next) {
3328 /* Octopus merge */
3329 struct child_process cmd = CHILD_PROCESS_INIT;
3330
3331 if (read_env_script(&cmd.env_array)) {
3332 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3333
3334 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3335 goto leave_merge;
3336 }
3337
3338 cmd.git_cmd = 1;
3339 argv_array_push(&cmd.args, "merge");
3340 argv_array_push(&cmd.args, "-s");
3341 argv_array_push(&cmd.args, "octopus");
3342 argv_array_push(&cmd.args, "--no-edit");
3343 argv_array_push(&cmd.args, "--no-ff");
3344 argv_array_push(&cmd.args, "--no-log");
3345 argv_array_push(&cmd.args, "--no-stat");
3346 argv_array_push(&cmd.args, "-F");
f11c9580 3347 argv_array_push(&cmd.args, git_path_merge_msg(r));
2b6ad0f4
JS
3348 if (opts->gpg_sign)
3349 argv_array_push(&cmd.args, opts->gpg_sign);
3350
3351 /* Add the tips to be merged */
3352 for (j = to_merge; j; j = j->next)
3353 argv_array_push(&cmd.args,
3354 oid_to_hex(&j->item->object.oid));
3355
3356 strbuf_release(&ref_name);
f11c9580 3357 unlink(git_path_cherry_pick_head(r));
2b6ad0f4
JS
3358 rollback_lock_file(&lock);
3359
3360 rollback_lock_file(&lock);
3361 ret = run_command(&cmd);
3362
3363 /* force re-reading of the cache */
f11c9580 3364 if (!ret && (discard_index(r->index) < 0 ||
e1ff0a32 3365 repo_read_index(r) < 0))
2b6ad0f4
JS
3366 ret = error(_("could not read index"));
3367 goto leave_merge;
3368 }
3369
3370 merge_commit = to_merge->item;
4c68e7dd 3371 bases = get_merge_bases(head_commit, merge_commit);
4a7e27e9
JK
3372 if (bases && oideq(&merge_commit->object.oid,
3373 &bases->item->object.oid)) {
7ccdf65b
JS
3374 ret = 0;
3375 /* skip merging an ancestor of HEAD */
3376 goto leave_merge;
3377 }
3378
85f8d9da 3379 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
cde55548
JH
3380 git_path_merge_head(r), 0);
3381 write_message("no-ff", 5, git_path_merge_mode(r), 0);
85f8d9da 3382
4c68e7dd
JS
3383 for (j = bases; j; j = j->next)
3384 commit_list_insert(j->item, &reversed);
3385 free_commit_list(bases);
3386
e1ff0a32 3387 repo_read_index(r);
0d6caa2d 3388 init_merge_options(&o, r);
4c68e7dd
JS
3389 o.branch1 = "HEAD";
3390 o.branch2 = ref_name.buf;
3391 o.buffer_output = 2;
3392
3393 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3394 if (ret <= 0)
3395 fputs(o.obuf.buf, stdout);
3396 strbuf_release(&o.obuf);
3397 if (ret < 0) {
3398 error(_("could not even attempt to merge '%.*s'"),
3399 merge_arg_len, arg);
3400 goto leave_merge;
3401 }
3402 /*
3403 * The return value of merge_recursive() is 1 on clean, and 0 on
3404 * unclean merge.
3405 *
3406 * Let's reverse that, so that do_merge() returns 0 upon success and
3407 * 1 upon failed merge (keeping the return value -1 for the cases where
3408 * we will want to reschedule the `merge` command).
3409 */
3410 ret = !ret;
3411
f11c9580
NTND
3412 if (r->index->cache_changed &&
3413 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4c68e7dd
JS
3414 ret = error(_("merge: Unable to write new index file"));
3415 goto leave_merge;
3416 }
3417
3418 rollback_lock_file(&lock);
3419 if (ret)
f11c9580 3420 repo_rerere(r, opts->allow_rerere_auto);
4c68e7dd
JS
3421 else
3422 /*
3423 * In case of problems, we now want to return a positive
3424 * value (a negative one would indicate that the `merge`
3425 * command needs to be rescheduled).
3426 */
f11c9580
NTND
3427 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3428 run_commit_flags);
4c68e7dd
JS
3429
3430leave_merge:
3431 strbuf_release(&ref_name);
3432 rollback_lock_file(&lock);
2b6ad0f4 3433 free_commit_list(to_merge);
4c68e7dd
JS
3434 return ret;
3435}
3436
6e98de72
JS
3437static int is_final_fixup(struct todo_list *todo_list)
3438{
3439 int i = todo_list->current;
3440
3441 if (!is_fixup(todo_list->items[i].command))
3442 return 0;
3443
3444 while (++i < todo_list->nr)
3445 if (is_fixup(todo_list->items[i].command))
3446 return 0;
3447 else if (!is_noop(todo_list->items[i].command))
3448 break;
3449 return 1;
3450}
3451
25cb8df9
JS
3452static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3453{
3454 int i;
3455
3456 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3457 if (!is_noop(todo_list->items[i].command))
3458 return todo_list->items[i].command;
3459
3460 return -1;
3461}
3462
796c7972
JS
3463static int apply_autostash(struct replay_opts *opts)
3464{
3465 struct strbuf stash_sha1 = STRBUF_INIT;
3466 struct child_process child = CHILD_PROCESS_INIT;
3467 int ret = 0;
3468
3469 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3470 strbuf_release(&stash_sha1);
3471 return 0;
3472 }
3473 strbuf_trim(&stash_sha1);
3474
3475 child.git_cmd = 1;
79a62269
PW
3476 child.no_stdout = 1;
3477 child.no_stderr = 1;
796c7972
JS
3478 argv_array_push(&child.args, "stash");
3479 argv_array_push(&child.args, "apply");
3480 argv_array_push(&child.args, stash_sha1.buf);
3481 if (!run_command(&child))
cdb866b3 3482 fprintf(stderr, _("Applied autostash.\n"));
796c7972
JS
3483 else {
3484 struct child_process store = CHILD_PROCESS_INIT;
3485
3486 store.git_cmd = 1;
3487 argv_array_push(&store.args, "stash");
3488 argv_array_push(&store.args, "store");
3489 argv_array_push(&store.args, "-m");
3490 argv_array_push(&store.args, "autostash");
3491 argv_array_push(&store.args, "-q");
3492 argv_array_push(&store.args, stash_sha1.buf);
3493 if (run_command(&store))
3494 ret = error(_("cannot store %s"), stash_sha1.buf);
3495 else
cdb866b3
JS
3496 fprintf(stderr,
3497 _("Applying autostash resulted in conflicts.\n"
3498 "Your changes are safe in the stash.\n"
3499 "You can run \"git stash pop\" or"
3500 " \"git stash drop\" at any time.\n"));
796c7972
JS
3501 }
3502
3503 strbuf_release(&stash_sha1);
3504 return ret;
3505}
3506
96e832a5
JS
3507static const char *reflog_message(struct replay_opts *opts,
3508 const char *sub_action, const char *fmt, ...)
3509{
3510 va_list ap;
3511 static struct strbuf buf = STRBUF_INIT;
3512
3513 va_start(ap, fmt);
3514 strbuf_reset(&buf);
3515 strbuf_addstr(&buf, action_name(opts));
3516 if (sub_action)
3517 strbuf_addf(&buf, " (%s)", sub_action);
3518 if (fmt) {
3519 strbuf_addstr(&buf, ": ");
3520 strbuf_vaddf(&buf, fmt, ap);
3521 }
3522 va_end(ap);
3523
3524 return buf.buf;
3525}
3526
2c58483a
AG
3527static int run_git_checkout(struct replay_opts *opts, const char *commit,
3528 const char *action)
3529{
3530 struct child_process cmd = CHILD_PROCESS_INIT;
3531
3532 cmd.git_cmd = 1;
3533
3534 argv_array_push(&cmd.args, "checkout");
3535 argv_array_push(&cmd.args, commit);
3536 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3537
3538 if (opts->verbose)
3539 return run_command(&cmd);
3540 else
3541 return run_command_silent_on_success(&cmd);
3542}
3543
3544int prepare_branch_to_be_rebased(struct replay_opts *opts, const char *commit)
3545{
3546 const char *action;
3547
3548 if (commit && *commit) {
3549 action = reflog_message(opts, "start", "checkout %s", commit);
3550 if (run_git_checkout(opts, commit, action))
3551 return error(_("could not checkout %s"), commit);
3552 }
3553
3554 return 0;
3555}
3556
91f0d95d
AG
3557static int checkout_onto(struct replay_opts *opts,
3558 const char *onto_name, const char *onto,
3559 const char *orig_head)
4df66c40
AG
3560{
3561 struct object_id oid;
3562 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3563
3564 if (get_oid(orig_head, &oid))
3565 return error(_("%s: not a valid OID"), orig_head);
3566
3567 if (run_git_checkout(opts, onto, action)) {
3568 apply_autostash(opts);
3569 sequencer_remove_state(opts);
3570 return error(_("could not detach HEAD"));
3571 }
3572
3573 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3574}
3575
005af339 3576static int stopped_at_head(struct repository *r)
71f82465
JS
3577{
3578 struct object_id head;
3579 struct commit *commit;
3580 struct commit_message message;
3581
789b1f70 3582 if (get_oid("HEAD", &head) ||
005af339 3583 !(commit = lookup_commit(r, &head)) ||
71f82465
JS
3584 parse_commit(commit) || get_message(commit, &message))
3585 fprintf(stderr, _("Stopped at HEAD\n"));
3586 else {
3587 fprintf(stderr, _("Stopped at %s\n"), message.label);
3588 free_message(commit, &message);
3589 }
3590 return 0;
3591
3592}
3593
cb5206ea
JS
3594static const char rescheduled_advice[] =
3595N_("Could not execute the todo command\n"
3596"\n"
3597" %.*s"
3598"\n"
3599"It has been rescheduled; To edit the command before continuing, please\n"