cherry-pick/revert: add scissors line on merge conflict
[git/git.git] / sequencer.c
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "dir.h"
5 #include "object-store.h"
6 #include "object.h"
7 #include "commit.h"
8 #include "sequencer.h"
9 #include "tag.h"
10 #include "run-command.h"
11 #include "exec-cmd.h"
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"
19 #include "argv-array.h"
20 #include "quote.h"
21 #include "trailer.h"
22 #include "log-tree.h"
23 #include "wt-status.h"
24 #include "hashmap.h"
25 #include "notes-utils.h"
26 #include "sigchain.h"
27 #include "unpack-trees.h"
28 #include "worktree.h"
29 #include "oidmap.h"
30 #include "oidset.h"
31 #include "commit-slab.h"
32 #include "alias.h"
33 #include "commit-reach.h"
34 #include "rebase-interactive.h"
35
36 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
37
38 static const char sign_off_header[] = "Signed-off-by: ";
39 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
40
41 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
42
43 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
44
45 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
46 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
47 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
48 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
49
50 static 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 */
57 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
58 static GIT_PATH_FUNC(rebase_path_todo_backup,
59 "rebase-merge/git-rebase-todo.backup")
60
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 */
66 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
67 /*
68 * The file to keep track of how many commands were already processed (e.g.
69 * for the prompt).
70 */
71 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
72 /*
73 * The file to keep track of how many commands are to be processed in total
74 * (e.g. for the prompt).
75 */
76 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
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 */
81 static 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.
89 */
90 static 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 */
98 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
99 /*
100 * This file contains the list fixup/squash commands that have been
101 * accumulated into message-fixup or message-squash so far.
102 */
103 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
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 */
109 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
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 */
118 static 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 */
123 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
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 */
130 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
131 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
132 "rebase-merge/rewritten-pending")
133
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 */
138 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
139
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 */
144 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
145
146 /*
147 * The following files are written by git-rebase just after parsing the
148 * command-line.
149 */
150 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
151 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
152 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
153 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
154 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
155 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
156 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
157 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
158 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
159 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
160 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
161 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
162
163 static 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
175 if (!strcmp(s, "verbatim")) {
176 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
177 opts->explicit_cleanup = 1;
178 } else if (!strcmp(s, "whitespace")) {
179 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
180 opts->explicit_cleanup = 1;
181 } else if (!strcmp(s, "strip")) {
182 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
183 opts->explicit_cleanup = 1;
184 } else if (!strcmp(s, "scissors")) {
185 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
186 opts->explicit_cleanup = 1;
187 } else {
188 warning(_("invalid commit message cleanup mode '%s'"),
189 s);
190 }
191
192 free((char *)s);
193 return status;
194 }
195
196 if (!strcmp(k, "commit.gpgsign")) {
197 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
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
208 void 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
214 static inline int is_rebase_i(const struct replay_opts *opts)
215 {
216 return opts->action == REPLAY_INTERACTIVE_REBASE;
217 }
218
219 static const char *get_dir(const struct replay_opts *opts)
220 {
221 if (is_rebase_i(opts))
222 return rebase_path();
223 return git_path_seq_dir();
224 }
225
226 static const char *get_todo_path(const struct replay_opts *opts)
227 {
228 if (is_rebase_i(opts))
229 return rebase_path_todo();
230 return git_path_todo_file();
231 }
232
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 */
239 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
240 size_t ignore_footer)
241 {
242 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
243 struct trailer_info info;
244 size_t i;
245 int found_sob = 0, found_sob_last = 0;
246
247 opts.no_divider = 1;
248
249 trailer_info_get(&info, sb->buf, &opts);
250
251 if (info.trailer_start == info.trailer_end)
252 return 0;
253
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 }
260
261 trailer_info_release(&info);
262
263 if (found_sob_last)
264 return 3;
265 if (found_sob)
266 return 2;
267 return 1;
268 }
269
270 static 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
280 int sequencer_remove_state(struct replay_opts *opts)
281 {
282 struct strbuf buf = STRBUF_INIT;
283 int i;
284
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
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);
305 strbuf_release(&opts->current_fixups);
306
307 strbuf_reset(&buf);
308 strbuf_addstr(&buf, get_dir(opts));
309 remove_dir_recursively(&buf, 0);
310 strbuf_release(&buf);
311
312 return 0;
313 }
314
315 static const char *action_name(const struct replay_opts *opts)
316 {
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 }
325 die(_("unknown action: %d"), opts->action);
326 }
327
328 struct commit_message {
329 char *parent_label;
330 char *label;
331 char *subject;
332 const char *message;
333 };
334
335 static const char *short_commit_name(struct commit *commit)
336 {
337 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
338 }
339
340 static int get_message(struct commit *commit, struct commit_message *out)
341 {
342 const char *abbrev, *subject;
343 int subject_len;
344
345 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
346 abbrev = short_commit_name(commit);
347
348 subject_len = find_commit_subject(out->message, &subject);
349
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
354 return 0;
355 }
356
357 static void free_message(struct commit *commit, struct commit_message *msg)
358 {
359 free(msg->parent_label);
360 free(msg->label);
361 free(msg->subject);
362 unuse_commit_buffer(commit, msg->message);
363 }
364
365 static void print_advice(struct repository *r, int show_hint,
366 struct replay_opts *opts)
367 {
368 char *msg = getenv("GIT_CHERRY_PICK_HELP");
369
370 if (msg) {
371 fprintf(stderr, "%s\n", msg);
372 /*
373 * A conflict has occurred but the porcelain
374 * (typically rebase --interactive) wants to take care
375 * of the commit itself so remove CHERRY_PICK_HEAD
376 */
377 unlink(git_path_cherry_pick_head(r));
378 return;
379 }
380
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 }
390 }
391
392 int write_message(const void *buf, size_t len, const char *filename,
393 int append_eol)
394 {
395 struct lock_file msg_file = LOCK_INIT;
396
397 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
398 if (msg_fd < 0)
399 return error_errno(_("could not lock '%s'"), filename);
400 if (write_in_full(msg_fd, buf, len) < 0) {
401 error_errno(_("could not write to '%s'"), filename);
402 rollback_lock_file(&msg_file);
403 return -1;
404 }
405 if (append_eol && write(msg_fd, "\n", 1) < 0) {
406 error_errno(_("could not write eol to '%s'"), filename);
407 rollback_lock_file(&msg_file);
408 return -1;
409 }
410 if (commit_lock_file(&msg_file) < 0)
411 return error(_("failed to finalize '%s'"), filename);
412
413 return 0;
414 }
415
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 */
425 static 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
450 static struct tree *empty_tree(struct repository *r)
451 {
452 return lookup_tree(r, the_hash_algo->empty_tree);
453 }
454
455 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
456 {
457 if (repo_read_index_unmerged(repo))
458 return error_resolve_conflict(_(action_name(opts)));
459
460 error(_("your local changes would be overwritten by %s."),
461 _(action_name(opts)));
462
463 if (advice_commit_before_merge)
464 advise(_("commit your changes or stash them to proceed."));
465 return -1;
466 }
467
468 static 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
482 static 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)
487 {
488 struct ref_transaction *transaction;
489 struct strbuf sb = STRBUF_INIT;
490 struct strbuf err = STRBUF_INIT;
491
492 repo_read_index(r);
493 if (checkout_fast_forward(r, from, to, 1))
494 return -1; /* the callee should have complained already */
495
496 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
497
498 transaction = ref_transaction_begin(&err);
499 if (!transaction ||
500 ref_transaction_update(transaction, "HEAD",
501 to, unborn && !is_rebase_i(opts) ?
502 &null_oid : from,
503 0, sb.buf, &err) ||
504 ref_transaction_commit(transaction, &err)) {
505 ref_transaction_free(transaction);
506 error("%s", err.buf);
507 strbuf_release(&sb);
508 strbuf_release(&err);
509 return -1;
510 }
511
512 strbuf_release(&sb);
513 strbuf_release(&err);
514 ref_transaction_free(transaction);
515 update_abort_safety_file();
516 return 0;
517 }
518
519 enum 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
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 */
543 static 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
556 void append_conflicts_hint(struct index_state *istate,
557 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
558 {
559 int i;
560
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
567 strbuf_addch(msgbuf, '\n');
568 strbuf_commented_addf(msgbuf, "Conflicts:\n");
569 for (i = 0; i < istate->cache_nr;) {
570 const struct cache_entry *ce = istate->cache[i++];
571 if (ce_stage(ce)) {
572 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
573 while (i < istate->cache_nr &&
574 !strcmp(ce->name, istate->cache[i]->name))
575 i++;
576 }
577 }
578 }
579
580 static int do_recursive_merge(struct repository *r,
581 struct commit *base, struct commit *next,
582 const char *base_label, const char *next_label,
583 struct object_id *head, struct strbuf *msgbuf,
584 struct replay_opts *opts)
585 {
586 struct merge_options o;
587 struct tree *result, *next_tree, *base_tree, *head_tree;
588 int clean;
589 char **xopt;
590 struct lock_file index_lock = LOCK_INIT;
591
592 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
593 return -1;
594
595 repo_read_index(r);
596
597 init_merge_options(&o, r);
598 o.ancestor = base ? base_label : "(empty tree)";
599 o.branch1 = "HEAD";
600 o.branch2 = next ? next_label : "(empty tree)";
601 if (is_rebase_i(opts))
602 o.buffer_output = 2;
603 o.show_rename_progress = 1;
604
605 head_tree = parse_tree_indirect(head);
606 next_tree = next ? get_commit_tree(next) : empty_tree(r);
607 base_tree = base ? get_commit_tree(base) : empty_tree(r);
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);
615 if (is_rebase_i(opts) && clean <= 0)
616 fputs(o.obuf.buf, stdout);
617 strbuf_release(&o.obuf);
618 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
619 if (clean < 0) {
620 rollback_lock_file(&index_lock);
621 return clean;
622 }
623
624 if (write_locked_index(r->index, &index_lock,
625 COMMIT_LOCK | SKIP_IF_UNCHANGED))
626 /*
627 * TRANSLATORS: %s will be "revert", "cherry-pick" or
628 * "rebase -i".
629 */
630 return error(_("%s: Unable to write new index file"),
631 _(action_name(opts)));
632
633 if (!clean)
634 append_conflicts_hint(r->index, msgbuf,
635 opts->default_msg_cleanup);
636
637 return !clean;
638 }
639
640 static struct object_id *get_cache_tree_oid(struct index_state *istate)
641 {
642 if (!istate->cache_tree)
643 istate->cache_tree = cache_tree();
644
645 if (!cache_tree_fully_valid(istate->cache_tree))
646 if (cache_tree_update(istate, 0)) {
647 error(_("unable to update cache tree"));
648 return NULL;
649 }
650
651 return &istate->cache_tree->oid;
652 }
653
654 static int is_index_unchanged(struct repository *r)
655 {
656 struct object_id head_oid, *cache_tree_oid;
657 struct commit *head_commit;
658 struct index_state *istate = r->index;
659
660 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
661 return error(_("could not resolve HEAD commit"));
662
663 head_commit = lookup_commit(r, &head_oid);
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;
675
676 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
677 return -1;
678
679 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
680 }
681
682 static 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")) {
690 missing_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
708 strbuf_addf(&buf, "'\\%c'", *(message++));
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
716 strbuf_addf(&buf, "'\\%c'", *(message++));
717 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
718 while (*message && *message != '\n' && *message != '\r')
719 if (*message != '\'')
720 strbuf_addch(&buf, *(message++));
721 else
722 strbuf_addf(&buf, "'\\%c'", *(message++));
723 strbuf_addch(&buf, '\'');
724 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
725 strbuf_release(&buf);
726 return res;
727 }
728
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 */
733 static 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 }
758
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.
775 */
776 int read_author_script(const char *path, char **name, char **email, char **date,
777 int allow_missing)
778 {
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;
783
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;
829 finish:
830 string_list_clear(&kv, !!retval);
831 strbuf_release(&buf);
832 return retval;
833 }
834
835 /*
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.
839 */
840 static int read_env_script(struct argv_array *env)
841 {
842 char *name, *email, *date;
843
844 if (read_author_script(rebase_path_author_script(),
845 &name, &email, &date, 0))
846 return -1;
847
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);
854
855 return 0;
856 }
857
858 static 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
870 /* Read author-script and return an ident line (author <email> timestamp) */
871 static const char *read_author_ident(struct strbuf *buf)
872 {
873 struct strbuf out = STRBUF_INIT;
874 char *name, *email, *date;
875
876 if (read_author_script(rebase_path_author_script(),
877 &name, &email, &date, 0))
878 return NULL;
879
880 /* validate date since fmt_ident() will die() on bad value */
881 if (parse_date(date, &out)){
882 warning(_("invalid date format '%s' in '%s'"),
883 date, rebase_path_author_script());
884 strbuf_release(&out);
885 return NULL;
886 }
887
888 strbuf_reset(&out);
889 strbuf_addstr(&out, fmt_ident(name, email, WANT_AUTHOR_IDENT, date, 0));
890 strbuf_swap(buf, &out);
891 strbuf_release(&out);
892 free(name);
893 free(email);
894 free(date);
895 return buf->buf;
896 }
897
898 static const char staged_changes_advice[] =
899 N_("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
912 #define ALLOW_EMPTY (1<<0)
913 #define EDIT_MSG (1<<1)
914 #define AMEND_MSG (1<<2)
915 #define CLEANUP_MSG (1<<3)
916 #define VERIFY_MSG (1<<4)
917 #define CREATE_ROOT_COMMIT (1<<5)
918
919 static 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
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.
940 *
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.
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.
947 */
948 static int run_git_commit(struct repository *r,
949 const char *defmsg,
950 struct replay_opts *opts,
951 unsigned int flags)
952 {
953 struct child_process cmd = CHILD_PROCESS_INIT;
954
955 if ((flags & CREATE_ROOT_COMMIT) && !(flags & AMEND_MSG)) {
956 struct strbuf msg = STRBUF_INIT, script = STRBUF_INIT;
957 const char *author = NULL;
958 struct object_id root_commit, *cache_tree_oid;
959 int res = 0;
960
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
969 if (!defmsg)
970 BUG("root commit without message");
971
972 if (!(cache_tree_oid = get_cache_tree_oid(r->index)))
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
996 cmd.git_cmd = 1;
997
998 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
999 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1000
1001 return error(_(staged_changes_advice),
1002 gpg_opt, gpg_opt);
1003 }
1004
1005 argv_array_push(&cmd.args, "commit");
1006
1007 if (!(flags & VERIFY_MSG))
1008 argv_array_push(&cmd.args, "-n");
1009 if ((flags & AMEND_MSG))
1010 argv_array_push(&cmd.args, "--amend");
1011 if (opts->gpg_sign)
1012 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1013 if (defmsg)
1014 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
1015 else if (!(flags & EDIT_MSG))
1016 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
1017 if ((flags & CLEANUP_MSG))
1018 argv_array_push(&cmd.args, "--cleanup=strip");
1019 if ((flags & EDIT_MSG))
1020 argv_array_push(&cmd.args, "-e");
1021 else if (!(flags & CLEANUP_MSG) &&
1022 !opts->signoff && !opts->record_origin &&
1023 !opts->explicit_cleanup)
1024 argv_array_push(&cmd.args, "--cleanup=verbatim");
1025
1026 if ((flags & ALLOW_EMPTY))
1027 argv_array_push(&cmd.args, "--allow-empty");
1028
1029 if (!(flags & EDIT_MSG))
1030 argv_array_push(&cmd.args, "--allow-empty-message");
1031
1032 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1033 return run_command_silent_on_success(&cmd);
1034 else
1035 return run_command(&cmd);
1036 }
1037
1038 static 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
1064 void 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
1074 /*
1075 * Find out if the message in the strbuf contains only whitespace and
1076 * Signed-off-by lines.
1077 */
1078 int 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 */
1090 int 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
1109 int 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
1146 static 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;
1164 proc.trace2_hook_name = "post-rewrite";
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
1178 void commit_post_rewrite(struct repository *r,
1179 const struct commit *old_head,
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);
1188 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1189 }
1190 run_rewrite_hook(&old_head->object.oid, new_head);
1191 }
1192
1193 static int run_prepare_commit_msg_hook(struct repository *r,
1194 struct strbuf *msg,
1195 const char *commit)
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
1205 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", r->index_file);
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
1220 static const char implicit_ident_advice_noconfig[] =
1221 N_("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
1233 static const char implicit_ident_advice_config[] =
1234 N_("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
1245 static 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
1261 void print_commit_summary(struct repository *r,
1262 const char *prefix,
1263 const struct object_id *oid,
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
1274 commit = lookup_commit(r, oid);
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
1307 repo_init_revisions(r, &rev, prefix);
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;
1318 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
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
1341 static int parse_head(struct repository *r, struct commit **head)
1342 {
1343 struct commit *current_head;
1344 struct object_id oid;
1345
1346 if (get_oid("HEAD", &oid)) {
1347 current_head = NULL;
1348 } else {
1349 current_head = lookup_commit_reference(r, &oid);
1350 if (!current_head)
1351 return error(_("could not parse HEAD"));
1352 if (!oideq(&oid, &current_head->object.oid)) {
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 */
1373 static int try_to_commit(struct repository *r,
1374 struct strbuf *msg, const char *author,
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;
1383 struct strbuf commit_msg = STRBUF_INIT;
1384 char *amend_author = NULL;
1385 const char *hook_commit = NULL;
1386 enum commit_msg_cleanup_mode cleanup;
1387 int res = 0;
1388
1389 if (parse_head(r, &current_head))
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);
1402 msg = &commit_msg;
1403 strbuf_addstr(msg, orig_message);
1404 hook_commit = "HEAD";
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
1418 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1419 res = error(_("git write-tree failed to write a tree"));
1420 goto out;
1421 }
1422
1423 if (!(flags & ALLOW_EMPTY) && oideq(current_head ?
1424 get_commit_tree_oid(current_head) :
1425 the_hash_algo->empty_tree, &tree)) {
1426 res = 1; /* run 'git commit' to display error message */
1427 goto out;
1428 }
1429
1430 if (find_hook("prepare-commit-msg")) {
1431 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
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
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;
1451
1452 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1453 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1454 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1455 res = 1; /* run 'git commit' to display error message */
1456 goto out;
1457 }
1458
1459 reset_ident_date();
1460
1461 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1462 oid, author, opts->gpg_sign, extra)) {
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)
1474 commit_post_rewrite(r, current_head, oid);
1475
1476 out:
1477 free_commit_extra_headers(extra);
1478 strbuf_release(&err);
1479 strbuf_release(&commit_msg);
1480 free(amend_author);
1481
1482 return res;
1483 }
1484
1485 static int do_commit(struct repository *r,
1486 const char *msg_file, const char *author,
1487 struct replay_opts *opts, unsigned int flags)
1488 {
1489 int res = 1;
1490
1491 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG) &&
1492 !(flags & CREATE_ROOT_COMMIT)) {
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
1501 res = try_to_commit(r, msg_file ? &sb : NULL,
1502 author, opts, flags, &oid);
1503 strbuf_release(&sb);
1504 if (!res) {
1505 unlink(git_path_cherry_pick_head(r));
1506 unlink(git_path_merge_msg(r));
1507 if (!is_rebase_i(opts))
1508 print_commit_summary(r, NULL, &oid,
1509 SUMMARY_SHOW_AUTHOR_DATE);
1510 return res;
1511 }
1512 }
1513 if (res == 1)
1514 return run_git_commit(r, msg_file, opts, flags);
1515
1516 return res;
1517 }
1518
1519 static int is_original_commit_empty(struct commit *commit)
1520 {
1521 const struct object_id *ptree_oid;
1522
1523 if (parse_commit(commit))
1524 return error(_("could not parse commit %s"),
1525 oid_to_hex(&commit->object.oid));
1526 if (commit->parents) {
1527 struct commit *parent = commit->parents->item;
1528 if (parse_commit(parent))
1529 return error(_("could not parse parent commit %s"),
1530 oid_to_hex(&parent->object.oid));
1531 ptree_oid = get_commit_tree_oid(parent);
1532 } else {
1533 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1534 }
1535
1536 return oideq(ptree_oid, get_commit_tree_oid(commit));
1537 }
1538
1539 /*
1540 * Do we run "git commit" with "--allow-empty"?
1541 */
1542 static int allow_empty(struct repository *r,
1543 struct replay_opts *opts,
1544 struct commit *commit)
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
1561 index_unchanged = is_index_unchanged(r);
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
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 */
1584 enum todo_command {
1585 /* commands that handle commits */
1586 TODO_PICK = 0,
1587 TODO_REVERT,
1588 TODO_EDIT,
1589 TODO_REWORD,
1590 TODO_FIXUP,
1591 TODO_SQUASH,
1592 /* commands that do something else than handling a single commit */
1593 TODO_EXEC,
1594 TODO_BREAK,
1595 TODO_LABEL,
1596 TODO_RESET,
1597 TODO_MERGE,
1598 /* commands that do nothing but are counted for reporting progress */
1599 TODO_NOOP,
1600 TODO_DROP,
1601 /* comments (not counted for reporting progress) */
1602 TODO_COMMENT
1603 };
1604
1605 static struct {
1606 char c;
1607 const char *str;
1608 } todo_command_info[] = {
1609 { 'p', "pick" },
1610 { 0, "revert" },
1611 { 'e', "edit" },
1612 { 'r', "reword" },
1613 { 'f', "fixup" },
1614 { 's', "squash" },
1615 { 'x', "exec" },
1616 { 'b', "break" },
1617 { 'l', "label" },
1618 { 't', "reset" },
1619 { 'm', "merge" },
1620 { 0, "noop" },
1621 { 'd', "drop" },
1622 { 0, NULL }
1623 };
1624
1625 static const char *command_to_string(const enum todo_command command)
1626 {
1627 if (command < TODO_COMMENT)
1628 return todo_command_info[command].str;
1629 die(_("unknown command: %d"), command);
1630 }
1631
1632 static char command_to_char(const enum todo_command command)
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
1639 static int is_noop(const enum todo_command command)
1640 {
1641 return TODO_NOOP <= command;
1642 }
1643
1644 static int is_fixup(enum todo_command command)
1645 {
1646 return command == TODO_FIXUP || command == TODO_SQUASH;
1647 }
1648
1649 /* Does this command create a (non-merge) commit? */
1650 static 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
1665 static int update_squash_messages(struct repository *r,
1666 enum todo_command command,
1667 struct commit *commit,
1668 struct replay_opts *opts)
1669 {
1670 struct strbuf buf = STRBUF_INIT;
1671 int res;
1672 const char *message, *body;
1673
1674 if (opts->current_fixup_count > 0) {
1675 struct strbuf header = STRBUF_INIT;
1676 char *eol;
1677
1678 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1679 return error(_("could not read '%s'"),
1680 rebase_path_squash_msg());
1681
1682 eol = buf.buf[0] != comment_line_char ?
1683 buf.buf : strchrnul(buf.buf, '\n');
1684
1685 strbuf_addf(&header, "%c ", comment_line_char);
1686 strbuf_addf(&header, _("This is a combination of %d commits."),
1687 opts->current_fixup_count + 2);
1688 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1689 strbuf_release(&header);
1690 } else {
1691 struct object_id head;
1692 struct commit *head_commit;
1693 const char *head_message, *body;
1694
1695 if (get_oid("HEAD", &head))
1696 return error(_("need a HEAD to fixup"));
1697 if (!(head_commit = lookup_commit_reference(r, &head)))
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
1710 strbuf_addf(&buf, "%c ", comment_line_char);
1711 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
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);
1728 strbuf_addf(&buf, _("This is the commit message #%d:"),
1729 ++opts->current_fixup_count + 1);
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:"),
1735 ++opts->current_fixup_count + 1);
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);
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
1755 return res;
1756 }
1757
1758 static void flush_rewritten_pending(void)
1759 {
1760 struct strbuf buf = STRBUF_INIT;
1761 struct object_id newoid;
1762 FILE *out;
1763
1764 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1765 !get_oid("HEAD", &newoid) &&
1766 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1767 char *bol = buf.buf, *eol;
1768
1769 while (*bol) {
1770 eol = strchrnul(bol, '\n');
1771 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1772 bol, oid_to_hex(&newoid));
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
1783 static void record_in_rewritten(struct object_id *oid,
1784 enum todo_command next_command)
1785 {
1786 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
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
1798 static 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)
1803 {
1804 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1805 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
1806 struct object_id head;
1807 struct commit *base, *next, *parent;
1808 const char *base_label, *next_label;
1809 char *author = NULL;
1810 struct commit_message msg = { NULL, NULL, NULL, NULL };
1811 struct strbuf msgbuf = STRBUF_INIT;
1812 int res, unborn = 0, allow;
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 */
1821 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
1822 return error(_("your index file is unmerged."));
1823 } else {
1824 unborn = get_oid("HEAD", &head);
1825 /* Do we want to generate a root commit? */
1826 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1827 oideq(&head, &opts->squash_onto)) {
1828 if (is_fixup(command))
1829 return error(_("cannot fixup root commit"));
1830 flags |= CREATE_ROOT_COMMIT;
1831 unborn = 1;
1832 } else if (unborn)
1833 oidcpy(&head, the_hash_algo->empty_tree);
1834 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
1835 NULL, 0))
1836 return error_dirty_index(r, opts);
1837 }
1838 discard_index(r->index);
1839
1840 if (!commit->parents)
1841 parent = NULL;
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)
1848 return error(_("commit %s is a merge but no -m option was given."),
1849 oid_to_hex(&commit->object.oid));
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)
1856 return error(_("commit %s does not have parent %d"),
1857 oid_to_hex(&commit->object.oid), opts->mainline);
1858 parent = p->item;
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);
1866 else
1867 parent = commit->parents->item;
1868
1869 if (get_message(commit, &msg) != 0)
1870 return error(_("cannot get commit message for %s"),
1871 oid_to_hex(&commit->object.oid));
1872
1873 if (opts->allow_ff && !is_fixup(command) &&
1874 ((parent && oideq(&parent->object.oid, &head)) ||
1875 (!parent && unborn))) {
1876 if (is_rebase_i(opts))
1877 write_author_script(msg.message);
1878 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
1879 opts);
1880 if (res || command != TODO_REWORD)
1881 goto leave;
1882 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1883 msg_file = NULL;
1884 goto fast_forward_edit;
1885 }
1886 if (parent && parse_commit(parent) < 0)
1887 /* TRANSLATORS: The first %s will be a "todo" command like
1888 "revert" or "pick", the second %s a SHA1. */
1889 return error(_("%s: cannot parse parent commit %s"),
1890 command_to_string(command),
1891 oid_to_hex(&parent->object.oid));
1892
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
1900 if (command == TODO_REVERT) {
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 ");
1908 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1909
1910 if (commit->parents && commit->parents->next) {
1911 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1912 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
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
1923 /* Append the commit log message to msgbuf. */
1924 if (find_commit_subject(msg.message, &p))
1925 strbuf_addstr(&msgbuf, p);
1926
1927 if (opts->record_origin) {
1928 strbuf_complete_line(&msgbuf);
1929 if (!has_conforming_footer(&msgbuf, NULL, 0))
1930 strbuf_addch(&msgbuf, '\n');
1931 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1932 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1933 strbuf_addstr(&msgbuf, ")\n");
1934 }
1935 if (!is_fixup(command))
1936 author = get_author(msg.message);
1937 }
1938
1939 if (command == TODO_REWORD)
1940 flags |= EDIT_MSG | VERIFY_MSG;
1941 else if (is_fixup(command)) {
1942 if (update_squash_messages(r, command, commit, opts))
1943 return -1;
1944 flags |= AMEND_MSG;
1945 if (!final_fixup)
1946 msg_file = rebase_path_squash_msg();
1947 else if (file_exists(rebase_path_fixup_msg())) {
1948 flags |= CLEANUP_MSG;
1949 msg_file = rebase_path_fixup_msg();
1950 } else {
1951 const char *dest = git_path_squash_msg(r);
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);
1956 unlink(git_path_merge_msg(r));
1957 msg_file = dest;
1958 flags |= EDIT_MSG;
1959 }
1960 }
1961
1962 if (opts->signoff && !is_fixup(command))
1963 append_signoff(&msgbuf, 0, 0);
1964
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) {
1968 res = do_recursive_merge(r, base, next, base_label, next_label,
1969 &head, &msgbuf, opts);
1970 if (res < 0)
1971 goto leave;
1972
1973 res |= write_message(msgbuf.buf, msgbuf.len,
1974 git_path_merge_msg(r), 0);
1975 } else {
1976 struct commit_list *common = NULL;
1977 struct commit_list *remotes = NULL;
1978
1979 res = write_message(msgbuf.buf, msgbuf.len,
1980 git_path_merge_msg(r), 0);
1981
1982 commit_list_insert(base, &common);
1983 commit_list_insert(next, &remotes);
1984 res |= try_merge_command(r, opts->strategy,
1985 opts->xopts_nr, (const char **)opts->xopts,
1986 common, oid_to_hex(&head), remotes);
1987 free_commit_list(common);
1988 free_commit_list(remotes);
1989 }
1990 strbuf_release(&msgbuf);
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 */
1998 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1999 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2000 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2001 res = -1;
2002 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2003 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2004 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2005 res = -1;
2006
2007 if (res) {
2008 error(command == TODO_REVERT
2009 ? _("could not revert %s... %s")
2010 : _("could not apply %s... %s"),
2011 short_commit_name(commit), msg.subject);
2012 print_advice(r, res == 1, opts);
2013 repo_rerere(r, opts->allow_rerere_auto);
2014 goto leave;
2015 }
2016
2017 allow = allow_empty(r, opts, commit);
2018 if (allow < 0) {
2019 res = allow;
2020 goto leave;
2021 } else if (allow)
2022 flags |= ALLOW_EMPTY;
2023 if (!opts->no_commit) {
2024 fast_forward_edit:
2025 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2026 res = do_commit(r, msg_file, author, opts, flags);
2027 else
2028 res = error(_("unable to parse commit author"));
2029 }
2030
2031 if (!res && final_fixup) {
2032 unlink(rebase_path_fixup_msg());
2033 unlink(rebase_path_squash_msg());
2034 unlink(rebase_path_current_fixups());
2035 strbuf_reset(&opts->current_fixups);
2036 opts->current_fixup_count = 0;
2037 }
2038
2039 leave:
2040 free_message(commit, &msg);
2041 free(author);
2042 update_abort_safety_file();
2043
2044 return res;
2045 }
2046
2047 static int prepare_revs(struct replay_opts *opts)
2048 {
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)
2054 opts->revs->reverse ^= 1;
2055
2056 if (prepare_revision_walk(opts->revs))
2057 return error(_("revision walk setup failed"));
2058
2059 return 0;
2060 }
2061
2062 static int read_and_refresh_cache(struct repository *r,
2063 struct replay_opts *opts)
2064 {
2065 struct lock_file index_lock = LOCK_INIT;
2066 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2067 if (repo_read_index(r) < 0) {
2068 rollback_lock_file(&index_lock);
2069 return error(_("git %s: failed to read the index"),
2070 _(action_name(opts)));
2071 }
2072 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2073 if (index_fd >= 0) {
2074 if (write_locked_index(r->index, &index_lock,
2075 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2076 return error(_("git %s: failed to refresh the index"),
2077 _(action_name(opts)));
2078 }
2079 }
2080 return 0;
2081 }
2082
2083 enum todo_item_flags {
2084 TODO_EDIT_MERGE_MSG = 1
2085 };
2086
2087 struct todo_item {
2088 enum todo_command command;
2089 struct commit *commit;
2090 unsigned int flags;
2091 const char *arg;
2092 int arg_len;
2093 size_t offset_in_buf;
2094 };
2095
2096 struct todo_list {
2097 struct strbuf buf;
2098 struct todo_item *items;
2099 int nr, alloc, current;
2100 int done_nr, total_nr;
2101 struct stat_data stat;
2102 };
2103
2104 #define TODO_LIST_INIT { STRBUF_INIT }
2105
2106 static void todo_list_release(struct todo_list *todo_list)
2107 {
2108 strbuf_release(&todo_list->buf);
2109 FREE_AND_NULL(todo_list->items);
2110 todo_list->nr = todo_list->alloc = 0;
2111 }
2112
2113 static 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++;
2117 }
2118
2119 static int parse_insn_line(struct repository *r, struct todo_item *item,
2120 const char *bol, char *eol)
2121 {
2122 struct object_id commit_oid;
2123 char *end_of_object_name;
2124 int i, saved, status, padding;
2125
2126 item->flags = 0;
2127
2128 /* left-trim */
2129 bol += strspn(bol, " \t");
2130
2131 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2132 item->command = TODO_COMMENT;
2133 item->commit = NULL;
2134 item->arg = bol;
2135 item->arg_len = eol - bol;
2136 return 0;
2137 }
2138
2139 for (i = 0; i < TODO_COMMENT; i++)
2140 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
2141 item->command = i;
2142 break;
2143 } else if ((bol + 1 == eol || bol[1] == ' ') &&
2144 *bol == todo_command_info[i].c) {
2145 bol++;
2146 item->command = i;
2147 break;
2148 }
2149 if (i >= TODO_COMMENT)
2150 return -1;
2151
2152 /* Eat up extra spaces/ tabs before object name */
2153 padding = strspn(bol, " \t");
2154 bol += padding;
2155
2156 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2157 if (bol != eol)
2158 return error(_("%s does not accept arguments: '%s'"),
2159 command_to_string(item->command), bol);
2160 item->commit = NULL;
2161 item->arg = bol;
2162 item->arg_len = eol - bol;
2163 return 0;
2164 }
2165
2166 if (!padding)
2167 return error(_("missing arguments for %s"),
2168 command_to_string(item->command));
2169
2170 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2171 item->command == TODO_RESET) {
2172 item->commit = NULL;
2173 item->arg = bol;
2174 item->arg_len = (int)(eol - bol);
2175 return 0;
2176 }
2177
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
2193 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2194 saved = *end_of_object_name;
2195 *end_of_object_name = '\0';
2196 status = get_oid(bol, &commit_oid);
2197 *end_of_object_name = saved;
2198
2199 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
2200 item->arg_len = (int)(eol - item->arg);
2201
2202 if (status < 0)
2203 return error(_("could not parse '%.*s'"),
2204 (int)(end_of_object_name - bol), bol);
2205
2206 item->commit = lookup_commit_reference(r, &commit_oid);
2207 return !item->commit;
2208 }
2209
2210 static int parse_insn_buffer(struct repository *r, char *buf,
2211 struct todo_list *todo_list)
2212 {
2213 struct todo_item *item;
2214 char *p = buf, *next_p;
2215 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2216
2217 for (i = 1; *p; i++, p = next_p) {
2218 char *eol = strchrnul(p, '\n');
2219
2220 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2221
2222 if (p != eol && eol[-1] == '\r')
2223 eol--; /* strip Carriage Return */
2224
2225 item = append_new_todo(todo_list);
2226 item->offset_in_buf = p - todo_list->buf.buf;
2227 if (parse_insn_line(r, item, p, eol)) {
2228 res = error(_("invalid line %d: %.*s"),
2229 i, (int)(eol - p), p);
2230 item->command = TODO_NOOP;
2231 }
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;
2240 }
2241
2242 return res;
2243 }
2244
2245 static 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
2256 static 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
2262 static 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
2267 static 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
2273 static 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
2288 static int read_populate_todo(struct repository *r,
2289 struct todo_list *todo_list,
2290 struct replay_opts *opts)
2291 {
2292 struct stat st;
2293 const char *todo_file = get_todo_path(opts);
2294 int res;
2295
2296 strbuf_reset(&todo_list->buf);
2297 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2298 return -1;
2299
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
2305 res = parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2306 if (res) {
2307 if (is_rebase_i(opts))
2308 return error(_("please fix this using "
2309 "'git rebase --edit-todo'."));
2310 return error(_("unusable instruction sheet: '%s'"), todo_file);
2311 }
2312
2313 if (!todo_list->nr &&
2314 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2315 return error(_("no commits parsed."));
2316
2317 if (!is_rebase_i(opts)) {
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)
2326 return error(_("cannot cherry-pick during a revert."));
2327 else
2328 return error(_("cannot revert during a cherry-pick."));
2329 }
2330
2331 if (is_rebase_i(opts)) {
2332 struct todo_list done = TODO_LIST_INIT;
2333 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2334
2335 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2336 !parse_insn_buffer(r, done.buf.buf, &done))
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);
2343 todo_list_release(&done);
2344
2345 if (f) {
2346 fprintf(f, "%d\n", todo_list->total_nr);
2347 fclose(f);
2348 }
2349 }
2350
2351 return 0;
2352 }
2353
2354 static 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
2364 static 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"))
2384 git_config_string_dup(&opts->strategy, key, value);
2385 else if (!strcmp(key, "options.gpg-sign"))
2386 git_config_string_dup(&opts->gpg_sign, key, value);
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);
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;
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
2398 return error(_("invalid key: %s"), key);
2399
2400 if (!error_flag)
2401 return error(_("invalid value for %s: %s"), key, value);
2402
2403 return 0;
2404 }
2405
2406 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2407 {
2408 int i;
2409 char *strategy_opts_string = raw_opts;
2410
2411 if (*strategy_opts_string == ' ')
2412 strategy_opts_string++;
2413
2414 opts->xopts_nr = split_cmdline(strategy_opts_string,
2415 (const char ***)&opts->xopts);
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
2424 static 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
2436 static int read_populate_opts(struct replay_opts *opts)
2437 {
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 }
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);
2457 }
2458
2459 if (file_exists(rebase_path_verbose()))
2460 opts->verbose = 1;
2461
2462 if (file_exists(rebase_path_quiet()))
2463 opts->quiet = 1;
2464
2465 if (file_exists(rebase_path_signoff())) {
2466 opts->allow_ff = 0;
2467 opts->signoff = 1;
2468 }
2469
2470 if (file_exists(rebase_path_reschedule_failed_exec()))
2471 opts->reschedule_failed_exec = 1;
2472
2473 read_strategy_opts(opts, &buf);
2474 strbuf_release(&buf);
2475
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
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
2492 return 0;
2493 }
2494
2495 if (!file_exists(git_path_opts_file()))
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 */
2503 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2504 return error(_("malformed options sheet: '%s'"),
2505 git_path_opts_file());
2506 return 0;
2507 }
2508
2509 static 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
2521 int 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);
2535 if (opts->verbose)
2536 write_file(rebase_path_verbose(), "%s", "");
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");
2551 if (opts->reschedule_failed_exec)
2552 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2553
2554 return 0;
2555 }
2556
2557 static int walk_revs_populate_todo(struct todo_list *todo_list,
2558 struct replay_opts *opts)
2559 {
2560 enum todo_command command = opts->action == REPLAY_PICK ?
2561 TODO_PICK : TODO_REVERT;
2562 const char *command_string = todo_command_info[command].str;
2563 struct commit *commit;
2564
2565 if (prepare_revs(opts))
2566 return -1;
2567
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;
2576 item->arg = NULL;
2577 item->arg_len = 0;
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 }
2584
2585 if (!todo_list->nr)
2586 return error(_("empty commit set passed"));
2587
2588 return 0;
2589 }
2590
2591 static int create_seq_dir(void)
2592 {
2593 if (file_exists(git_path_seq_dir())) {
2594 error(_("a cherry-pick or revert is already in progress"));
2595 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2596 return -1;
2597 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2598 return error_errno(_("could not create sequencer directory '%s'"),
2599 git_path_seq_dir());
2600 return 0;
2601 }
2602
2603 static int save_head(const char *head)
2604 {
2605 struct lock_file head_lock = LOCK_INIT;
2606 struct strbuf buf = STRBUF_INIT;
2607 int fd;
2608 ssize_t written;
2609
2610 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2611 if (fd < 0)
2612 return error_errno(_("could not lock HEAD"));
2613 strbuf_addf(&buf, "%s\n", head);
2614 written = write_in_full(fd, buf.buf, buf.len);
2615 strbuf_release(&buf);
2616 if (written < 0) {
2617 error_errno(_("could not write to '%s'"), git_path_head_file());
2618 rollback_lock_file(&head_lock);
2619 return -1;
2620 }
2621 if (commit_lock_file(&head_lock) < 0)
2622 return error(_("failed to finalize '%s'"), git_path_head_file());
2623 return 0;
2624 }
2625
2626 static 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
2647 return oideq(&actual_head, &expected_head);
2648 }
2649
2650 static int reset_for_rollback(const struct object_id *oid)
2651 {
2652 const char *argv[4]; /* reset --merge <arg> + NULL */
2653
2654 argv[0] = "reset";
2655 argv[1] = "--merge";
2656 argv[2] = oid_to_hex(oid);
2657 argv[3] = NULL;
2658 return run_command_v_opt(argv, RUN_GIT_CMD);
2659 }
2660
2661 static int rollback_single_pick(struct repository *r)
2662 {
2663 struct object_id head_oid;
2664
2665 if (!file_exists(git_path_cherry_pick_head(r)) &&
2666 !file_exists(git_path_revert_head(r)))
2667 return error(_("no cherry-pick or revert in progress"));
2668 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2669 return error(_("cannot resolve HEAD"));
2670 if (is_null_oid(&head_oid))
2671 return error(_("cannot abort from a branch yet to be born"));
2672 return reset_for_rollback(&head_oid);
2673 }
2674
2675 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2676 {
2677 FILE *f;
2678 struct object_id oid;
2679 struct strbuf buf = STRBUF_INIT;
2680 const char *p;
2681
2682 f = fopen(git_path_head_file(), "r");
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 */
2689 return rollback_single_pick(r);
2690 }
2691 if (!f)
2692 return error_errno(_("cannot open '%s'"), git_path_head_file());
2693 if (strbuf_getline_lf(&buf, f)) {
2694 error(_("cannot read '%s': %s"), git_path_head_file(),
2695 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2696 fclose(f);
2697 goto fail;
2698 }
2699 fclose(f);
2700 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2701 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2702 git_path_head_file());
2703 goto fail;
2704 }
2705 if (is_null_oid(&oid)) {
2706 error(_("cannot abort from a branch yet to be born"));
2707 goto fail;
2708 }
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
2715 if (reset_for_rollback(&oid))
2716 goto fail;
2717 strbuf_release(&buf);
2718 return sequencer_remove_state(opts);
2719 fail:
2720 strbuf_release(&buf);
2721 return -1;
2722 }
2723
2724 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2725 {
2726 struct lock_file todo_lock = LOCK_INIT;
2727 const char *todo_path = get_todo_path(opts);
2728 int next = todo_list->current, offset, fd;
2729
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
2737 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2738 if (fd < 0)
2739 return error_errno(_("could not lock '%s'"), todo_path);
2740 offset = get_item_line_offset(todo_list, next);
2741 if (write_in_full(fd, todo_list->buf.buf + offset,
2742 todo_list->buf.len - offset) < 0)
2743 return error_errno(_("could not write to '%s'"), todo_path);
2744 if (commit_lock_file(&todo_lock) < 0)
2745 return error(_("failed to finalize '%s'"), todo_path);
2746
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;
2751
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;
2761 }
2762 return 0;
2763 }
2764
2765 static int save_opts(struct replay_opts *opts)
2766 {
2767 const char *opts_file = git_path_opts_file();
2768 int res = 0;
2769
2770 if (opts->no_commit)
2771 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2772 if (opts->edit)
2773 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2774 if (opts->signoff)
2775 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2776 if (opts->record_origin)
2777 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2778 if (opts->allow_ff)
2779 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2780 if (opts->mainline) {
2781 struct strbuf buf = STRBUF_INIT;
2782 strbuf_addf(&buf, "%d", opts->mainline);
2783 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2784 strbuf_release(&buf);
2785 }
2786 if (opts->strategy)
2787 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2788 if (opts->gpg_sign)
2789 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2790 if (opts->xopts) {
2791 int i;
2792 for (i = 0; i < opts->xopts_nr; i++)
2793 res |= git_config_set_multivar_in_file_gently(opts_file,
2794 "options.strategy-option",
2795 opts->xopts[i], "^$", 0);
2796 }
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");
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));
2806 return res;
2807 }
2808
2809 static int make_patch(struct repository *r,
2810 struct commit *commit,
2811 struct replay_opts *opts)
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;
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");
2824
2825 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2826 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2827 repo_init_revisions(r, &log_tree_opt, NULL);
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
2855 static int intend_to_amend(void)
2856 {
2857 struct object_id head;
2858 char *p;
2859
2860 if (get_oid("HEAD", &head))
2861 return error(_("cannot read HEAD"));
2862
2863 p = oid_to_hex(&head);
2864 return write_message(p, strlen(p), rebase_path_amend(), 1);
2865 }
2866
2867 static 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)
2872 {
2873 if (commit) {
2874 if (make_patch(r, commit, opts))
2875 return -1;
2876 } else if (copy_file(rebase_path_message(),
2877 git_path_merge_msg(r), 0666))
2878 return error(_("unable to copy '%s' to '%s'"),
2879 git_path_merge_msg(r), rebase_path_message());
2880
2881 if (to_amend) {
2882 if (intend_to_amend())
2883 return -1;
2884
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));
2894 } else if (exit_code) {
2895 if (commit)
2896 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
2897 short_commit_name(commit), subject_len, subject);
2898 else
2899 /*
2900 * We don't have the hash of the parent so
2901 * just print the line from the todo file.
2902 */
2903 fprintf_ln(stderr, _("Could not merge %.*s"),
2904 subject_len, subject);
2905 }
2906
2907 return exit_code;
2908 }
2909
2910 static int error_failed_squash(struct repository *r,
2911 struct commit *commit,
2912 struct replay_opts *opts,
2913 int subject_len,
2914 const char *subject)
2915 {
2916 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
2917 return error(_("could not copy '%s' to '%s'"),
2918 rebase_path_squash_msg(), rebase_path_message());
2919 unlink(git_path_merge_msg(r));
2920 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
2921 return error(_("could not copy '%s' to '%s'"),
2922 rebase_path_message(),
2923 git_path_merge_msg(r));
2924 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
2925 }
2926
2927 static int do_exec(struct repository *r, const char *command_line)
2928 {
2929 struct argv_array child_env = ARGV_ARRAY_INIT;
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;
2935 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2936 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
2937 absolute_path(get_git_work_tree()));
2938 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2939 child_env.argv);
2940
2941 /* force re-reading of the cache */
2942 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
2943 return error(_("could not read index"));
2944
2945 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
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
2969 argv_array_clear(&child_env);
2970
2971 return status;
2972 }
2973
2974 static 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
3011 static int do_label(struct repository *r, const char *name, int len)
3012 {
3013 struct ref_store *refs = get_main_ref_store(r);
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 == '#')
3021 return error(_("illegal label name: '%.*s'"), len, name);
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
3051 static const char *reflog_message(struct replay_opts *opts,
3052 const char *sub_action, const char *fmt, ...);
3053
3054 static int do_reset(struct repository *r,
3055 const char *name, int len,
3056 struct replay_opts *opts)
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;
3064 int ret = 0;
3065
3066 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3067 return -1;
3068
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 {
3084 int i;
3085
3086 /* Determine the length of the label */
3087 for (i = 0; i < len; i++)
3088 if (isspace(name[i]))
3089 break;
3090 len = i;
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 }
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;
3105 unpack_tree_opts.src_index = r->index;
3106 unpack_tree_opts.dst_index = r->index;
3107 unpack_tree_opts.fn = oneway_merge;
3108 unpack_tree_opts.merge = 1;
3109 unpack_tree_opts.update = 1;
3110
3111 if (repo_read_index_unmerged(r)) {
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);
3133 prime_cache_tree(r, r->index, tree);
3134
3135 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
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
3148 static 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
3168 static int do_merge(struct repository *r,
3169 struct commit *commit,
3170 const char *arg, int arg_len,
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;
3178 struct commit_list *to_merge = NULL, **tail = &to_merge;
3179 struct merge_options o;
3180 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3181 static struct lock_file lock;
3182 const char *p;
3183
3184 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
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
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;
3219 }
3220
3221 if (!to_merge) {
3222 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3223 goto leave_merge;
3224 }
3225
3226 if (opts->have_squash_onto &&
3227 oideq(&head_commit->object.oid, &opts->squash_onto)) {
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);
3233 if (to_merge->next)
3234 ret = error(_("octopus merge cannot be executed on "
3235 "top of a [new root]"));
3236 else
3237 ret = fast_forward_to(r, &to_merge->item->object.oid,
3238 &head_commit->object.oid, 0,
3239 opts);
3240 goto leave_merge;
3241 }
3242
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);
3256 ret = write_message(body, len, git_path_merge_msg(r), 0);
3257 unuse_commit_buffer(commit, message);
3258 if (ret) {
3259 error_errno(_("could not write '%s'"),
3260 git_path_merge_msg(r));
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 {
3275 strbuf_addf(&buf, "Merge %s '%.*s'",
3276 to_merge->next ? "branches" : "branch",
3277 merge_arg_len, arg);
3278 p = buf.buf;
3279 len = buf.len;
3280 }
3281
3282 ret = write_message(p, len, git_path_merge_msg(r), 0);
3283 strbuf_release(&buf);
3284 if (ret) {
3285 error_errno(_("could not write '%s'"),
3286 git_path_merge_msg(r));
3287 goto leave_merge;
3288 }
3289 }
3290
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 &&
3296 oideq(&commit->parents->item->object.oid,
3297 &head_commit->object.oid);
3298
3299 /*
3300 * If any merge head is different from the original one, we cannot
3301 * fast-forward.
3302 */
3303 if (can_fast_forward) {
3304 struct commit_list *p = commit->parents->next;
3305
3306 for (j = to_merge; j && p; j = j->next, p = p->next)
3307 if (!oideq(&j->item->object.oid,
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)
3317 can_fast_forward = 0;
3318 }
3319
3320 if (can_fast_forward) {
3321 rollback_lock_file(&lock);
3322 ret = fast_forward_to(r, &commit->object.oid,
3323 &head_commit->object.oid, 0, opts);
3324 goto leave_merge;
3325 }
3326
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");
3347 argv_array_push(&cmd.args, git_path_merge_msg(r));
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);
3357 unlink(git_path_cherry_pick_head(r));
3358 rollback_lock_file(&lock);
3359
3360 rollback_lock_file(&lock);
3361 ret = run_command(&cmd);
3362
3363 /* force re-reading of the cache */
3364 if (!ret && (discard_index(r->index) < 0 ||
3365 repo_read_index(r) < 0))
3366 ret = error(_("could not read index"));
3367 goto leave_merge;
3368 }
3369
3370 merge_commit = to_merge->item;
3371 bases = get_merge_bases(head_commit, merge_commit);
3372 if (bases && oideq(&merge_commit->object.oid,
3373 &bases->item->object.oid)) {
3374 ret = 0;
3375 /* skip merging an ancestor of HEAD */
3376 goto leave_merge;
3377 }
3378
3379 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
3380 git_path_merge_head(r), 0);
3381 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3382
3383 for (j = bases; j; j = j->next)
3384 commit_list_insert(j->item, &reversed);
3385 free_commit_list(bases);
3386
3387 repo_read_index(r);
3388 init_merge_options(&o, r);
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
3412 if (r->index->cache_changed &&
3413 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3414 ret = error(_("merge: Unable to write new index file"));
3415 goto leave_merge;
3416 }
3417
3418 rollback_lock_file(&lock);
3419 if (ret)
3420 repo_rerere(r, opts->allow_rerere_auto);
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 */
3427 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3428 run_commit_flags);
3429
3430 leave_merge:
3431 strbuf_release(&ref_name);
3432 rollback_lock_file(&lock);
3433 free_commit_list(to_merge);
3434 return ret;
3435 }
3436
3437 static 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
3452 static 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
3463 static 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;
3476 child.no_stdout = 1;
3477 child.no_stderr = 1;
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))
3482 fprintf(stderr, _("Applied autostash.\n"));
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
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"));
3501 }
3502
3503 strbuf_release(&stash_sha1);
3504 return ret;
3505 }
3506
3507 static 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
3527 static 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
3544 int 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
3557 static int checkout_onto(struct replay_opts *opts,
3558 const char *onto_name, const char *onto,
3559 const char *orig_head)
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
3576 static int stopped_at_head(struct repository *r)
3577 {
3578 struct object_id head;
3579 struct commit *commit;
3580 struct commit_message message;
3581
3582 if (get_oid("HEAD", &head) ||
3583 !(commit = lookup_commit(r, &head)) ||
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
3594 static const char rescheduled_advice[] =
3595 N_("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"
3600 "edit the todo list first:\n"
3601 "\n"
3602 " git rebase --edit-todo\n"
3603 " git rebase --continue\n");
3604
3605 static int pick_commits(struct repository *r,
3606 struct todo_list *todo_list,
3607 struct replay_opts *opts)
3608 {
3609 int res = 0, reschedule = 0;
3610
3611 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3612 if (opts->allow_ff)
3613 assert(!(opts->signoff || opts->no_commit ||
3614 opts->record_origin || opts->edit));
3615 if (read_and_refresh_cache(r, opts))
3616 return -1;
3617
3618 while (todo_list->current < todo_list->nr) {
3619 struct todo_item *item = todo_list->items + todo_list->current;
3620 if (save_todo(todo_list, opts))
3621 return -1;
3622 if (is_rebase_i(opts)) {
3623 if (item->command != TODO_COMMENT) {
3624 FILE *f = fopen(rebase_path_msgnum(), "w");
3625
3626 todo_list->done_nr++;
3627
3628 if (f) {
3629 fprintf(f, "%d\n", todo_list->done_nr);
3630 fclose(f);
3631 }