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