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