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