Raw
1 #define USE_THE_REPOSITORY_VARIABLE
2
3 #include "builtin.h"
4 #include "advice.h"
5 #include "cache-tree.h"
6 #include "commit.h"
7 #include "commit-reach.h"
8 #include "config.h"
9 #include "editor.h"
10 #include "environment.h"
11 #include "gettext.h"
12 #include "hex.h"
13 #include "lockfile.h"
14 #include "merge-ort.h"
15 #include "oidmap.h"
16 #include "parse-options.h"
17 #include "path.h"
18 #include "read-cache.h"
19 #include "refs.h"
20 #include "replay.h"
21 #include "reset.h"
22 #include "revision.h"
23 #include "sequencer.h"
24 #include "strvec.h"
25 #include "tree.h"
26 #include "tree-walk.h"
27 #include "unpack-trees.h"
28 #include "wt-status.h"
29
30 #define GIT_HISTORY_DROP_USAGE \
31 N_("git history drop <commit> [--dry-run] [--update-refs=(branches|head)] [--empty=(drop|keep|abort)]")
32 #define GIT_HISTORY_FIXUP_USAGE \
33 N_("git history fixup <commit> [--dry-run] [--update-refs=(branches|head)] [--reedit-message] [--empty=(drop|keep|abort)]")
34 #define GIT_HISTORY_REWORD_USAGE \
35 N_("git history reword <commit> [--dry-run] [--update-refs=(branches|head)]")
36 #define GIT_HISTORY_SPLIT_USAGE \
37 N_("git history split <commit> [--dry-run] [--update-refs=(branches|head)] [--] [<pathspec>...]")
38 #define GIT_HISTORY_SQUASH_USAGE \
39 N_("git history squash [--dry-run] [--update-refs=(branches|head)] [--reedit-message] <revision-range>")
40
41 static void change_data_free(void *util, const char *str UNUSED)
42 {
43 struct wt_status_change_data *d = util;
44 free(d->rename_source);
45 free(d);
46 }
47
48 static int fill_commit_message(struct repository *repo,
49 const struct object_id *old_tree,
50 const struct object_id *new_tree,
51 const char *default_message,
52 const char *action,
53 struct strbuf *out)
54 {
55 const char *path = git_path_commit_editmsg();
56 const char *hint =
57 _("Please enter the commit message for the %s changes."
58 " Lines starting\nwith '%s' will be ignored, and an"
59 " empty message aborts the commit.\n");
60 struct wt_status s;
61
62 wt_status_prepare(repo, &s);
63 FREE_AND_NULL(s.branch);
64 s.ahead_behind_flags = AHEAD_BEHIND_QUICK;
65 s.commit_template = 1;
66 s.colopts = 0;
67 s.display_comment_prefix = 1;
68 s.hints = 0;
69 s.use_color = 0;
70 s.whence = FROM_COMMIT;
71 s.committable = 1;
72
73 s.fp = fopen(path, "w");
74 if (!s.fp)
75 return error_errno(_("could not open '%s'"), path);
76
77 strbuf_addstr(out, default_message);
78 strbuf_addch(out, '\n');
79 strbuf_commented_addf(out, comment_line_str, hint, action, comment_line_str);
80 if (fwrite(out->buf, 1, out->len, s.fp) != out->len)
81 die_errno(_("could not write to '%s'"), path);
82
83 wt_status_collect_changes_trees(&s, old_tree, new_tree);
84 wt_status_print(&s);
85 wt_status_collect_free_buffers(&s);
86 string_list_clear_func(&s.change, change_data_free);
87 if (fclose(s.fp))
88 die_errno(_("could not write to '%s'"), path);
89
90 strbuf_reset(out);
91 if (launch_editor(path, out, NULL)) {
92 fprintf(stderr, _("Aborting commit as launching the editor failed.\n"));
93 return -1;
94 }
95 strbuf_stripspace(out, comment_line_str);
96
97 cleanup_message(out, COMMIT_MSG_CLEANUP_ALL, 0);
98
99 if (!out->len) {
100 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
101 return -1;
102 }
103
104 return 0;
105 }
106
107 enum commit_tree_flags {
108 COMMIT_TREE_EDIT_MESSAGE = (1 << 0),
109 };
110
111 static int commit_tree_ext(struct repository *repo,
112 const char *action,
113 struct commit *commit_with_message,
114 const char *message_template,
115 const struct commit_list *parents,
116 const struct object_id *old_tree,
117 const struct object_id *new_tree,
118 struct commit **out,
119 enum commit_tree_flags flags)
120 {
121 const char *exclude_gpgsig[] = {
122 /* We reencode the message, so the encoding needs to be stripped. */
123 "encoding",
124 /* We need to strip signatures as those will become invalid. */
125 "gpgsig",
126 "gpgsig-sha256",
127 NULL,
128 };
129 const char *original_message, *original_body, *ptr;
130 struct commit_extra_header *original_extra_headers = NULL;
131 struct strbuf commit_message = STRBUF_INIT;
132 struct object_id rewritten_commit_oid;
133 char *original_author = NULL;
134 size_t len;
135 int ret;
136
137 /* We retain authorship of the original commit. */
138 original_message = repo_logmsg_reencode(repo, commit_with_message, NULL, NULL);
139 ptr = find_commit_header(original_message, "author", &len);
140 if (ptr)
141 original_author = xmemdupz(ptr, len);
142 find_commit_subject(original_message, &original_body);
143
144 if (!message_template)
145 message_template = original_body;
146
147 if (flags & COMMIT_TREE_EDIT_MESSAGE) {
148 ret = fill_commit_message(repo, old_tree, new_tree,
149 message_template, action, &commit_message);
150 if (ret < 0)
151 goto out;
152 } else {
153 strbuf_addstr(&commit_message, message_template);
154 }
155
156 original_extra_headers = read_commit_extra_headers(commit_with_message,
157 exclude_gpgsig);
158
159 ret = commit_tree_extended(commit_message.buf, commit_message.len, new_tree,
160 parents, &rewritten_commit_oid, original_author,
161 NULL, NULL, original_extra_headers);
162 if (ret < 0)
163 goto out;
164
165 *out = lookup_commit_or_die(&rewritten_commit_oid, "rewritten commit");
166
167 out:
168 free_commit_extra_headers(original_extra_headers);
169 strbuf_release(&commit_message);
170 free(original_author);
171 return ret;
172 }
173
174 static int first_parent_tree_oid(struct repository *repo,
175 struct commit *commit,
176 struct object_id *out)
177 {
178 struct commit *parent = commit->parents ? commit->parents->item : NULL;
179
180 if (!parent) {
181 oidcpy(out, repo->hash_algo->empty_tree);
182 return 0;
183 }
184
185 if (repo_parse_commit(repo, parent))
186 return error(_("unable to parse parent commit %s"),
187 oid_to_hex(&parent->object.oid));
188
189 oidcpy(out, &repo_get_commit_tree(repo, parent)->object.oid);
190 return 0;
191 }
192
193 static int commit_tree_with_edited_message(struct repository *repo,
194 const char *action,
195 struct commit *original,
196 struct commit **out)
197 {
198 struct object_id parent_tree_oid;
199 const struct object_id *tree_oid;
200
201 tree_oid = &repo_get_commit_tree(repo, original)->object.oid;
202
203 if (first_parent_tree_oid(repo, original, &parent_tree_oid) < 0)
204 return -1;
205
206 return commit_tree_ext(repo, action, original, NULL, original->parents,
207 &parent_tree_oid, tree_oid, out, COMMIT_TREE_EDIT_MESSAGE);
208 }
209
210 enum ref_action {
211 REF_ACTION_DEFAULT,
212 REF_ACTION_BRANCHES,
213 REF_ACTION_HEAD,
214 };
215
216 static int parse_ref_action(const struct option *opt, const char *value, int unset)
217 {
218 enum ref_action *action = opt->value;
219
220 BUG_ON_OPT_NEG_NOARG(unset, value);
221 if (!strcmp(value, "branches")) {
222 *action = REF_ACTION_BRANCHES;
223 } else if (!strcmp(value, "head")) {
224 *action = REF_ACTION_HEAD;
225 } else {
226 return error(_("%s expects one of 'branches' or 'head'"),
227 opt->long_name);
228 }
229
230 return 0;
231 }
232
233 static int revwalk_contains_merges(struct repository *repo,
234 const struct strvec *revwalk_args)
235 {
236 struct strvec args = STRVEC_INIT;
237 struct rev_info revs;
238 int ret;
239
240 strvec_pushv(&args, revwalk_args->v);
241 strvec_push(&args, "--min-parents=2");
242
243 repo_init_revisions(repo, &revs, NULL);
244
245 setup_revisions_from_strvec(&args, &revs, NULL);
246 if (args.nr != 1)
247 BUG("revisions were set up with invalid argument");
248
249 if (prepare_revision_walk(&revs) < 0) {
250 ret = error(_("error preparing revisions"));
251 goto out;
252 }
253
254 if (get_revision(&revs)) {
255 ret = error(_("replaying merge commits is not supported yet!"));
256 goto out;
257 }
258
259 reset_revision_walk();
260 ret = 0;
261
262 out:
263 release_revisions(&revs);
264 strvec_clear(&args);
265 return ret;
266 }
267
268 static int setup_revwalk(struct repository *repo,
269 enum ref_action action,
270 struct commit *original,
271 struct rev_info *revs)
272 {
273 struct strvec args = STRVEC_INIT;
274 int ret;
275
276 repo_init_revisions(repo, revs, NULL);
277 strvec_push(&args, "ignored");
278 strvec_push(&args, "--reverse");
279 strvec_push(&args, "--topo-order");
280 strvec_push(&args, "--full-history");
281
282 /* We only want to see commits that are descendants of the old commit. */
283 strvec_pushf(&args, "--ancestry-path=%s",
284 oid_to_hex(&original->object.oid));
285
286 /*
287 * Ancestry path may also show ancestors of the old commit, but we
288 * don't want to see those, either.
289 */
290 strvec_pushf(&args, "^%s", oid_to_hex(&original->object.oid));
291
292 /*
293 * When we're asked to update HEAD we need to verify that the commit
294 * that we want to rewrite is actually an ancestor of it and, if so,
295 * update it. Otherwise we'll update (or print) all descendant
296 * branches.
297 */
298 if (action == REF_ACTION_HEAD) {
299 struct commit_list *from_list = NULL;
300 struct commit *head;
301
302 head = lookup_commit_reference_by_name("HEAD");
303 if (!head) {
304 ret = error(_("cannot look up HEAD"));
305 goto out;
306 }
307
308 commit_list_insert(original, &from_list);
309 ret = repo_is_descendant_of(repo, head, from_list);
310 commit_list_free(from_list);
311
312 if (ret < 0) {
313 ret = error(_("cannot determine descendance"));
314 goto out;
315 } else if (!ret) {
316 ret = error(_("rewritten commit must be an ancestor "
317 "of HEAD when using --update-refs=head"));
318 goto out;
319 }
320
321 strvec_push(&args, "HEAD");
322 } else {
323 strvec_push(&args, "--branches");
324 strvec_push(&args, "HEAD");
325 }
326
327 ret = revwalk_contains_merges(repo, &args);
328 if (ret < 0)
329 goto out;
330
331 setup_revisions_from_strvec(&args, revs, NULL);
332 if (args.nr != 1)
333 BUG("revisions were set up with invalid argument");
334
335 ret = 0;
336
337 out:
338 strvec_clear(&args);
339 return ret;
340 }
341
342 static int handle_ref_update(struct ref_transaction *transaction,
343 const char *refname,
344 const struct object_id *new_oid,
345 const struct object_id *old_oid,
346 const char *reflog_msg,
347 struct strbuf *err)
348 {
349 if (!transaction) {
350 printf("update %s %s %s\n",
351 refname, oid_to_hex(new_oid), oid_to_hex(old_oid));
352 return 0;
353 }
354
355 return ref_transaction_update(transaction, refname, new_oid, old_oid,
356 NULL, NULL, 0, reflog_msg, err);
357 }
358
359 static int compute_pending_ref_updates(struct rev_info *revs,
360 enum ref_action action,
361 struct commit *original,
362 struct commit *rewritten,
363 enum replay_empty_commit_action empty,
364 struct replay_result *result)
365 {
366 const struct name_decoration *decoration;
367 struct replay_revisions_options opts = {
368 .empty = empty,
369 };
370 char hex[GIT_MAX_HEXSZ + 1];
371 bool detached_head;
372 int head_flags = 0;
373 int ret;
374
375 refs_read_ref_full(get_main_ref_store(revs->repo), "HEAD",
376 RESOLVE_REF_NO_RECURSE, NULL, &head_flags);
377 detached_head = !(head_flags & REF_ISSYMREF);
378
379 opts.onto = oid_to_hex_r(hex, &rewritten->object.oid);
380
381 ret = replay_revisions(revs, &opts, result);
382 if (ret)
383 return ret;
384
385 if (action != REF_ACTION_BRANCHES && action != REF_ACTION_HEAD)
386 BUG("unsupported ref action %d", action);
387
388 /*
389 * `replay_revisions()` only updates references that are
390 * ancestors of `rewritten`, so we need to manually
391 * handle updating references that point to `original`.
392 */
393 for (decoration = get_name_decoration(&original->object);
394 decoration;
395 decoration = decoration->next)
396 {
397 if (decoration->type != DECORATION_REF_LOCAL &&
398 decoration->type != DECORATION_REF_HEAD)
399 continue;
400
401 if (action == REF_ACTION_HEAD &&
402 decoration->type != DECORATION_REF_HEAD)
403 continue;
404
405 /*
406 * We only need to update HEAD separately in case it's
407 * detached. If it's not we'd already update the branch
408 * it is pointing to.
409 */
410 if (action == REF_ACTION_BRANCHES &&
411 decoration->type == DECORATION_REF_HEAD &&
412 !detached_head)
413 continue;
414
415 replay_result_queue_update(result, decoration->name,
416 &original->object.oid,
417 &rewritten->object.oid);
418 }
419
420 return 0;
421 }
422
423 static int apply_pending_ref_updates(struct repository *repo,
424 const struct replay_result *result,
425 const char *reflog_msg,
426 int dry_run)
427 {
428 struct ref_transaction *transaction = NULL;
429 struct strbuf err = STRBUF_INIT;
430 int ret;
431
432 if (!dry_run) {
433 transaction = ref_store_transaction_begin(get_main_ref_store(repo),
434 0, &err);
435 if (!transaction) {
436 ret = error(_("failed to begin ref transaction: %s"), err.buf);
437 goto out;
438 }
439 }
440
441 for (size_t i = 0; i < result->updates_nr; i++) {
442 ret = handle_ref_update(transaction,
443 result->updates[i].refname,
444 &result->updates[i].new_oid,
445 &result->updates[i].old_oid,
446 reflog_msg, &err);
447 if (ret) {
448 ret = error(_("failed to update ref '%s': %s"),
449 result->updates[i].refname, err.buf);
450 goto out;
451 }
452 }
453
454 if (transaction && ref_transaction_commit(transaction, &err)) {
455 ret = error(_("failed to commit ref transaction: %s"), err.buf);
456 goto out;
457 }
458
459 ret = 0;
460
461 out:
462 ref_transaction_free(transaction);
463 strbuf_release(&err);
464 return ret;
465 }
466
467 static int handle_reference_updates(struct rev_info *revs,
468 enum ref_action action,
469 struct commit *original,
470 struct commit *rewritten,
471 const char *reflog_msg,
472 int dry_run,
473 enum replay_empty_commit_action empty)
474 {
475 struct replay_result result = { 0 };
476 int ret;
477
478 ret = compute_pending_ref_updates(revs, action, original, rewritten,
479 empty, &result);
480 if (ret)
481 goto out;
482
483 ret = apply_pending_ref_updates(revs->repo, &result, reflog_msg, dry_run);
484
485 out:
486 replay_result_release(&result);
487 return ret;
488 }
489
490 static int commit_became_empty(struct repository *repo,
491 struct commit *original,
492 struct tree *result)
493 {
494 struct object_id parent_tree_oid;
495
496 if (first_parent_tree_oid(repo, original, &parent_tree_oid) < 0)
497 return -1;
498
499 return oideq(&result->object.oid, &parent_tree_oid);
500 }
501
502 static int parse_opt_empty(const struct option *opt, const char *arg, int unset)
503 {
504 enum replay_empty_commit_action *value = opt->value;
505
506 BUG_ON_OPT_NEG(unset);
507
508 if (!strcmp(arg, "drop"))
509 *value = REPLAY_EMPTY_COMMIT_DROP;
510 else if (!strcmp(arg, "keep"))
511 *value = REPLAY_EMPTY_COMMIT_KEEP;
512 else if (!strcmp(arg, "abort"))
513 *value = REPLAY_EMPTY_COMMIT_ABORT;
514 else
515 die(_("unrecognized '--empty=' action '%s'; "
516 "valid values are \"drop\", \"keep\", and \"abort\"."), arg);
517
518 return 0;
519 }
520
521 static int cmd_history_fixup(int argc,
522 const char **argv,
523 const char *prefix,
524 struct repository *repo)
525 {
526 const char * const usage[] = {
527 GIT_HISTORY_FIXUP_USAGE,
528 NULL,
529 };
530 enum replay_empty_commit_action empty = REPLAY_EMPTY_COMMIT_DROP;
531 enum ref_action action = REF_ACTION_DEFAULT;
532 enum commit_tree_flags flags = 0;
533 int dry_run = 0;
534 struct option options[] = {
535 OPT_CALLBACK_F(0, "update-refs", &action, "(branches|head)",
536 N_("control which refs should be updated"),
537 PARSE_OPT_NONEG, parse_ref_action),
538 OPT_BOOL('n', "dry-run", &dry_run,
539 N_("perform a dry-run without updating any refs")),
540 OPT_BIT(0, "reedit-message", &flags,
541 N_("open an editor to modify the commit message"),
542 COMMIT_TREE_EDIT_MESSAGE),
543 OPT_CALLBACK_F(0, "empty", &empty, "(drop|keep|abort)",
544 N_("how to handle commits that become empty"),
545 PARSE_OPT_NONEG, parse_opt_empty),
546 OPT_END(),
547 };
548 struct merge_result merge_result = { 0 };
549 struct merge_options merge_opts = { 0 };
550 struct strbuf reflog_msg = STRBUF_INIT;
551 struct commit *head_commit, *original, *rewritten;
552 struct tree *head_tree, *original_tree, *index_tree;
553 struct rev_info revs = { 0 };
554 bool skip_commit = false;
555 int ret;
556
557 argc = parse_options(argc, argv, prefix, options, usage, 0);
558 if (argc != 1) {
559 ret = error(_("command expects a single revision"));
560 goto out;
561 }
562 repo_config(repo, git_default_config, NULL);
563
564 if (action == REF_ACTION_DEFAULT)
565 action = REF_ACTION_BRANCHES;
566
567 if (is_bare_repository(repo)) {
568 ret = error(_("cannot run fixup in a bare repository"));
569 goto out;
570 }
571
572 /* Resolve the original commit, which is the one we want to fix up. */
573 original = lookup_commit_reference_by_name(argv[0]);
574 if (!original) {
575 ret = error(_("commit cannot be found: %s"), argv[0]);
576 goto out;
577 }
578
579 /*
580 * Resolve HEAD so we can use its tree as the merge base: the staged
581 * changes are expressed as a diff from HEAD's tree to the index tree.
582 */
583 head_commit = lookup_commit_reference_by_name("HEAD");
584 if (!head_commit) {
585 ret = error(_("cannot look up HEAD"));
586 goto out;
587 }
588
589 head_tree = repo_get_commit_tree(repo, head_commit);
590 if (!head_tree) {
591 ret = error(_("cannot get tree for HEAD"));
592 goto out;
593 }
594
595 if (repo_read_index(repo) < 0) {
596 ret = error(_("unable to read index"));
597 goto out;
598 }
599
600 if (!repo_index_has_changes(repo, head_tree, NULL)) {
601 ret = error(_("nothing to fixup: no staged changes"));
602 goto out;
603 }
604
605 /*
606 * Write the index as a tree object. This is the "theirs" side of the
607 * three-way merge: it is HEAD's tree with the staged changes applied.
608 */
609 index_tree = write_in_core_index_as_tree(repo, repo->index);
610 if (!index_tree) {
611 ret = error(_("unable to write index as a tree"));
612 goto out;
613 }
614
615 original_tree = repo_get_commit_tree(repo, original);
616 if (!original_tree) {
617 ret = error(_("cannot get tree for commit %s"), argv[0]);
618 goto out;
619 }
620
621 /*
622 * Perform the three-way merge to reapply changes in the index onto the
623 * target commit. This is using basically the same logic as a
624 * cherry-pick, where the base commit is our HEAD, ours is the original
625 * tree and theirs is the index tree.
626 */
627 init_basic_merge_options(&merge_opts, repo);
628 merge_opts.ancestor = "HEAD";
629 merge_opts.branch1 = argv[0];
630 merge_opts.branch2 = "staged";
631 merge_incore_nonrecursive(&merge_opts, head_tree,
632 original_tree, index_tree, &merge_result);
633
634 if (merge_result.clean < 0) {
635 ret = error(_("merge failed while applying fixup"));
636 goto out;
637 }
638
639 if (!merge_result.clean) {
640 ret = error(_("fixup would produce conflicts; aborting"));
641 goto out;
642 }
643
644 ret = commit_became_empty(repo, original, merge_result.tree);
645 if (ret < 0)
646 goto out;
647 if (ret > 0) {
648 switch (empty) {
649 case REPLAY_EMPTY_COMMIT_DROP:
650 /*
651 * Drop the target commit by replaying its descendants
652 * directly onto its parent.
653 */
654 rewritten = original->parents ? original->parents->item : NULL;
655
656 /*
657 * TODO: we don't yet have the ability to drop root
658 * commits, but there's ultimately no good reason for
659 * this restriction to exist other than a technical
660 * limitation.
661 */
662 if (!rewritten) {
663 ret = error(_("cannot drop root commit %s: "
664 "it has no parent to replay onto"),
665 argv[0]);
666 goto out;
667 }
668
669 skip_commit = true;
670 break;
671 case REPLAY_EMPTY_COMMIT_KEEP:
672 /* Proceed and record the empty commit. */
673 break;
674 case REPLAY_EMPTY_COMMIT_ABORT:
675 ret = error(_("fixup makes commit %s empty"), argv[0]);
676 goto out;
677 }
678 }
679
680 ret = setup_revwalk(repo, action, original, &revs);
681 if (ret)
682 goto out;
683
684 if (!skip_commit) {
685 ret = commit_tree_ext(repo, "fixup", original, NULL, original->parents,
686 &original_tree->object.oid, &merge_result.tree->object.oid,
687 &rewritten, flags);
688 if (ret < 0) {
689 ret = error(_("failed writing fixed-up commit"));
690 goto out;
691 }
692 }
693
694 strbuf_addf(&reflog_msg, "fixup: updating %s", argv[0]);
695
696 ret = handle_reference_updates(&revs, action, original, rewritten,
697 reflog_msg.buf, dry_run, empty);
698 if (ret < 0) {
699 ret = error(_("failed replaying descendants"));
700 goto out;
701 }
702
703 ret = 0;
704
705 out:
706 merge_finalize(&merge_opts, &merge_result);
707 strbuf_release(&reflog_msg);
708 release_revisions(&revs);
709 return ret;
710 }
711
712 static int cmd_history_reword(int argc,
713 const char **argv,
714 const char *prefix,
715 struct repository *repo)
716 {
717 const char * const usage[] = {
718 GIT_HISTORY_REWORD_USAGE,
719 NULL,
720 };
721 enum ref_action action = REF_ACTION_DEFAULT;
722 int dry_run = 0;
723 struct option options[] = {
724 OPT_CALLBACK_F(0, "update-refs", &action, "(branches|head)",
725 N_("control which refs should be updated"),
726 PARSE_OPT_NONEG, parse_ref_action),
727 OPT_BOOL('n', "dry-run", &dry_run,
728 N_("perform a dry-run without updating any refs")),
729 OPT_END(),
730 };
731 struct strbuf reflog_msg = STRBUF_INIT;
732 struct commit *original, *rewritten;
733 struct rev_info revs = { 0 };
734 int ret;
735
736 argc = parse_options(argc, argv, prefix, options, usage, 0);
737 if (argc != 1) {
738 ret = error(_("command expects a single revision"));
739 goto out;
740 }
741 repo_config(repo, git_default_config, NULL);
742
743 if (action == REF_ACTION_DEFAULT)
744 action = REF_ACTION_BRANCHES;
745
746 original = lookup_commit_reference_by_name(argv[0]);
747 if (!original) {
748 ret = error(_("commit cannot be found: %s"), argv[0]);
749 goto out;
750 }
751
752 ret = setup_revwalk(repo, action, original, &revs);
753 if (ret)
754 goto out;
755
756 ret = commit_tree_with_edited_message(repo, "reworded", original, &rewritten);
757 if (ret < 0) {
758 ret = error(_("failed writing reworded commit"));
759 goto out;
760 }
761
762 strbuf_addf(&reflog_msg, "reword: updating %s", argv[0]);
763
764 ret = handle_reference_updates(&revs, action, original, rewritten,
765 reflog_msg.buf, dry_run, REPLAY_EMPTY_COMMIT_ABORT);
766 if (ret < 0) {
767 ret = error(_("failed replaying descendants"));
768 goto out;
769 }
770
771 ret = 0;
772
773 out:
774 strbuf_release(&reflog_msg);
775 release_revisions(&revs);
776 return ret;
777 }
778
779 static int write_ondisk_index(struct repository *repo,
780 struct object_id *oid,
781 const char *path)
782 {
783 struct unpack_trees_options opts = { 0 };
784 struct lock_file lock = LOCK_INIT;
785 struct tree_desc tree_desc;
786 struct index_state index;
787 struct tree *tree;
788 int ret;
789
790 index_state_init(&index, repo);
791
792 opts.head_idx = -1;
793 opts.src_index = &index;
794 opts.dst_index = &index;
795
796 tree = repo_parse_tree_indirect(repo, oid);
797 init_tree_desc(&tree_desc, &tree->object.oid, tree->buffer, tree->size);
798
799 if (unpack_trees(1, &tree_desc, &opts)) {
800 ret = error(_("unable to populate index with tree"));
801 goto out;
802 }
803
804 prime_cache_tree(repo, &index, tree);
805
806 if (repo_hold_lock_file_for_update(repo, &lock, path, 0) < 0) {
807 ret = error_errno(_("unable to acquire index lock"));
808 goto out;
809 }
810
811 if (write_locked_index(&index, &lock, COMMIT_LOCK)) {
812 ret = error(_("unable to write new index file"));
813 goto out;
814 }
815
816 ret = 0;
817
818 out:
819 rollback_lock_file(&lock);
820 release_index(&index);
821 return ret;
822 }
823
824 static int split_commit(struct repository *repo,
825 struct commit *original,
826 struct pathspec *pathspec,
827 struct commit **out)
828 {
829 struct interactive_options interactive_opts = INTERACTIVE_OPTIONS_INIT;
830 struct strbuf index_file = STRBUF_INIT;
831 struct index_state index = INDEX_STATE_INIT(repo);
832 const struct object_id *original_commit_tree_oid;
833 const struct object_id *old_tree_oid, *new_tree_oid;
834 struct object_id parent_tree_oid;
835 char original_commit_oid[GIT_MAX_HEXSZ + 1];
836 struct commit *first_commit, *second_commit;
837 struct commit_list *parents = NULL;
838 struct tree *split_tree;
839 int ret;
840
841 if (first_parent_tree_oid(repo, original, &parent_tree_oid) < 0) {
842 ret = -1;
843 goto out;
844 }
845 original_commit_tree_oid = get_commit_tree_oid(original);
846
847 /*
848 * Construct the first commit. This is done by taking the original
849 * commit parent's tree and selectively patching changes from the diff
850 * between that parent and its child.
851 */
852 repo_git_path_replace(repo, &index_file, "%s", "history-split.index");
853
854 ret = write_ondisk_index(repo, &parent_tree_oid, index_file.buf);
855 if (ret < 0)
856 goto out;
857
858 ret = read_index_from(&index, index_file.buf, repo->gitdir);
859 if (ret < 0) {
860 ret = error(_("failed reading temporary index"));
861 goto out;
862 }
863
864 oid_to_hex_r(original_commit_oid, &original->object.oid);
865 ret = run_add_p_index(repo, &index, index_file.buf, &interactive_opts,
866 original_commit_oid, pathspec, ADD_P_DISALLOW_EDIT);
867 if (ret < 0)
868 goto out;
869
870 split_tree = write_in_core_index_as_tree(repo, &index);
871 if (!split_tree) {
872 ret = error(_("failed split tree"));
873 goto out;
874 }
875
876 unlink(index_file.buf);
877 strbuf_release(&index_file);
878
879 /*
880 * We disallow the cases where either the split-out commit or the
881 * original commit would become empty. Consequently, if we see that the
882 * new tree ID matches either of those trees we abort.
883 */
884 if (oideq(&split_tree->object.oid, &parent_tree_oid)) {
885 ret = error(_("split commit is empty"));
886 goto out;
887 } else if (oideq(&split_tree->object.oid, original_commit_tree_oid)) {
888 ret = error(_("split commit tree matches original commit"));
889 goto out;
890 }
891
892 /*
893 * The first commit is constructed from the split-out tree. The base
894 * that shall be diffed against is the parent of the original commit.
895 */
896 ret = commit_tree_ext(repo, "split-out", original, NULL, original->parents, &parent_tree_oid,
897 &split_tree->object.oid, &first_commit, COMMIT_TREE_EDIT_MESSAGE);
898 if (ret < 0) {
899 ret = error(_("failed writing first commit"));
900 goto out;
901 }
902
903 /*
904 * The second commit is constructed from the original tree. The base to
905 * diff against and the parent in this case is the first split-out
906 * commit.
907 */
908 commit_list_append(first_commit, &parents);
909
910 old_tree_oid = &repo_get_commit_tree(repo, first_commit)->object.oid;
911 new_tree_oid = &repo_get_commit_tree(repo, original)->object.oid;
912
913 ret = commit_tree_ext(repo, "split-out", original, NULL, parents, old_tree_oid,
914 new_tree_oid, &second_commit, COMMIT_TREE_EDIT_MESSAGE);
915 if (ret < 0) {
916 ret = error(_("failed writing second commit"));
917 goto out;
918 }
919
920 *out = second_commit;
921 ret = 0;
922
923 out:
924 if (index_file.len)
925 unlink(index_file.buf);
926 strbuf_release(&index_file);
927 commit_list_free(parents);
928 release_index(&index);
929 return ret;
930 }
931
932 static int cmd_history_split(int argc,
933 const char **argv,
934 const char *prefix,
935 struct repository *repo)
936 {
937 const char * const usage[] = {
938 GIT_HISTORY_SPLIT_USAGE,
939 NULL,
940 };
941 enum ref_action action = REF_ACTION_DEFAULT;
942 int dry_run = 0;
943 struct option options[] = {
944 OPT_CALLBACK_F(0, "update-refs", &action, "(branches|head)",
945 N_("control ref update behavior"),
946 PARSE_OPT_NONEG, parse_ref_action),
947 OPT_BOOL('n', "dry-run", &dry_run,
948 N_("perform a dry-run without updating any refs")),
949 OPT_END(),
950 };
951 struct commit *original, *rewritten = NULL;
952 struct strbuf reflog_msg = STRBUF_INIT;
953 struct pathspec pathspec = { 0 };
954 struct rev_info revs = { 0 };
955 int ret;
956
957 argc = parse_options(argc, argv, prefix, options, usage, 0);
958 if (argc < 1) {
959 ret = error(_("command expects a committish"));
960 goto out;
961 }
962 repo_config(repo, git_default_config, NULL);
963
964 if (action == REF_ACTION_DEFAULT)
965 action = REF_ACTION_BRANCHES;
966
967 parse_pathspec(&pathspec, 0,
968 PATHSPEC_PREFER_FULL |
969 PATHSPEC_SYMLINK_LEADING_PATH |
970 PATHSPEC_PREFIX_ORIGIN,
971 prefix, argv + 1);
972
973 original = lookup_commit_reference_by_name(argv[0]);
974 if (!original) {
975 ret = error(_("commit cannot be found: %s"), argv[0]);
976 goto out;
977 }
978
979 ret = setup_revwalk(repo, action, original, &revs);
980 if (ret < 0)
981 goto out;
982
983 if (original->parents && original->parents->next) {
984 ret = error(_("cannot split up merge commit"));
985 goto out;
986 }
987
988 ret = split_commit(repo, original, &pathspec, &rewritten);
989 if (ret < 0)
990 goto out;
991
992 strbuf_addf(&reflog_msg, "split: updating %s", argv[0]);
993
994 ret = handle_reference_updates(&revs, action, original, rewritten,
995 reflog_msg.buf, dry_run, REPLAY_EMPTY_COMMIT_ABORT);
996 if (ret < 0) {
997 ret = error(_("failed replaying descendants"));
998 goto out;
999 }
1000
1001 ret = 0;
1002
1003 out:
1004 strbuf_release(&reflog_msg);
1005 clear_pathspec(&pathspec);
1006 release_revisions(&revs);
1007 return ret;
1008 }
1009
1010 /*
1011 * Resolve a "<base>..<tip>" revision range into the base commit just outside
1012 * the range (which becomes the parent of the squashed commit), the oldest
1013 * commit contained in the range (whose message the squash reuses), and the
1014 * range tip (whose tree becomes the result). A merge inside the range is fine,
1015 * but the range must have a single base and must not reach a root commit.
1016 */
1017 static int resolve_squash_range(struct repository *repo,
1018 const char **argv,
1019 struct commit **base_out,
1020 struct commit **oldest_out,
1021 struct commit **tip_out,
1022 struct oidset *interior_out)
1023 {
1024 struct rev_info revs;
1025 struct commit *commit, *base = NULL, *oldest = NULL, *tip = NULL;
1026 struct commit_list *boundaries = NULL, *b;
1027 struct strvec args = STRVEC_INIT;
1028 size_t i;
1029 int ret;
1030
1031 repo_init_revisions(repo, &revs, NULL);
1032 revs.reverse = 1;
1033 revs.topo_order = 1;
1034 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
1035 revs.simplify_history = 0;
1036 revs.boundary = 1;
1037
1038 strvec_push(&args, "ignored");
1039 strvec_push(&args, "--ancestry-path");
1040 strvec_pushv(&args, argv);
1041 setup_revisions_from_strvec(&args, &revs, NULL);
1042 if (args.nr != 1) {
1043 ret = error(_("unrecognized argument: %s"), args.v[1]);
1044 goto out;
1045 }
1046
1047 if (revs.reverse != 1 || revs.topo_order != 1 ||
1048 revs.sort_order != REV_SORT_IN_GRAPH_ORDER ||
1049 revs.simplify_history != 0 || revs.boundary != 1) {
1050 warning(_("ignoring rev-list options that would change how the "
1051 "range is walked"));
1052 revs.reverse = 1;
1053 revs.topo_order = 1;
1054 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
1055 revs.simplify_history = 0;
1056 revs.boundary = 1;
1057 }
1058
1059 /*
1060 * A squash needs a base to reparent onto, so the range has to exclude
1061 * something, as in "<base>..<tip>". A revision range with no such
1062 * bottom commit cannot be squashed.
1063 */
1064 for (i = 0; i < revs.cmdline.nr; i++)
1065 if (revs.cmdline.rev[i].flags & UNINTERESTING)
1066 break;
1067 if (i == revs.cmdline.nr) {
1068 ret = error(_("not a '<base>..<tip>' revision range"));
1069 goto out;
1070 }
1071
1072 if (prepare_revision_walk(&revs) < 0) {
1073 ret = error(_("error preparing revisions"));
1074 goto out;
1075 }
1076
1077 /*
1078 * Set boundary commits aside for the base check below, and put every
1079 * in-range commit but the tip into the interior set. A ref pointing
1080 * at an interior commit would dangle once the range is folded away.
1081 */
1082 while ((commit = get_revision(&revs))) {
1083 if (commit->object.flags & BOUNDARY) {
1084 commit_list_insert(commit, &boundaries);
1085 continue;
1086 }
1087 if (!oldest)
1088 oldest = commit;
1089 if (tip)
1090 oidset_insert(interior_out, &tip->object.oid);
1091 tip = commit;
1092 }
1093
1094 if (!oldest) {
1095 ret = error(_("the revision range is empty"));
1096 goto out;
1097 } else if (oldest == tip) {
1098 ret = error(_("the revision range holds a single commit; "
1099 "nothing to squash"));
1100 goto out;
1101 } else if (!oldest->parents) {
1102 BUG("an in-range commit must have a parent");
1103 }
1104 base = oldest->parents->item;
1105
1106 /*
1107 * A boundary other than the base is an in-range commit reaching a
1108 * commit outside the range, so the range has more than one base.
1109 */
1110 for (b = boundaries; b; b = b->next) {
1111 if (b->item != base) {
1112 ret = error(_("the revision range has more than one base; "
1113 "cannot squash"));
1114 goto out;
1115 }
1116 }
1117
1118 *base_out = base;
1119 *oldest_out = oldest;
1120 *tip_out = tip;
1121 ret = 0;
1122
1123 out:
1124 commit_list_free(boundaries);
1125 reset_revision_walk();
1126 release_revisions(&revs);
1127 strvec_clear(&args);
1128 return ret;
1129 }
1130
1131 static const char *autosquash_target(const char *subject)
1132 {
1133 const char *rest;
1134
1135 while (skip_prefix(subject, "fixup! ", &rest) ||
1136 skip_prefix(subject, "squash! ", &rest) ||
1137 skip_prefix(subject, "amend! ", &rest))
1138 subject = rest;
1139 return subject;
1140 }
1141
1142 static int reject_dangling_fixups(struct repository *repo,
1143 struct commit *base,
1144 struct commit *tip,
1145 struct commit *oldest,
1146 struct commit **msg_source,
1147 struct commit **amend_source)
1148 {
1149 struct todo_list todo = TODO_LIST_INIT;
1150 struct replay_opts opts = REPLAY_OPTS_INIT;
1151 struct rev_info revs;
1152 struct commit *commit, *last_amend = NULL;
1153 struct strvec args = STRVEC_INIT;
1154 char *dangling_subject = NULL, *dangling_target = NULL;
1155 bool mixed_target = false, all_fixups_one_target;
1156 bool past_oldest_group = false;
1157 int i, ret, nr_dangling = 0;
1158
1159 *msg_source = oldest;
1160 *amend_source = NULL;
1161
1162 repo_init_revisions(repo, &revs, NULL);
1163 strvec_push(&args, "ignored");
1164 strvec_push(&args, "--reverse");
1165 strvec_push(&args, "--topo-order");
1166 strvec_pushf(&args, "%s..%s", oid_to_hex(&base->object.oid),
1167 oid_to_hex(&tip->object.oid));
1168 setup_revisions_from_strvec(&args, &revs, NULL);
1169
1170 if (prepare_revision_walk(&revs) < 0) {
1171 ret = error(_("error preparing revisions"));
1172 goto out;
1173 }
1174 while ((commit = get_revision(&revs)))
1175 strbuf_addf(&todo.buf, "pick %s\n",
1176 oid_to_hex(&commit->object.oid));
1177
1178 if (todo_list_parse_insn_buffer(repo, &opts, todo.buf.buf, &todo) < 0 ||
1179 todo_list_rearrange_squash(&todo) < 0) {
1180 ret = error(_("could not check the range for fixups"));
1181 goto out;
1182 }
1183
1184 for (i = 0; i < todo.nr; i++) {
1185 const char *message, *subject_start, *target;
1186 char *subject;
1187 size_t sublen;
1188
1189 message = repo_logmsg_reencode(repo, todo.items[i].commit,
1190 NULL, NULL);
1191 sublen = find_commit_subject(message, &subject_start);
1192
1193 if (todo.items[i].command != TODO_PICK) {
1194 if (!past_oldest_group &&
1195 starts_with(subject_start, "amend! "))
1196 *amend_source = todo.items[i].commit;
1197 repo_unuse_commit_buffer(repo, todo.items[i].commit, message);
1198 continue;
1199 }
1200 if (i)
1201 past_oldest_group = true;
1202
1203 subject = xmemdupz(subject_start, sublen);
1204 target = autosquash_target(subject);
1205 if (target != subject) {
1206 nr_dangling++;
1207 if (!dangling_target) {
1208 dangling_target = xstrdup(target);
1209 dangling_subject = xstrdup(subject);
1210 } else if (strcmp(dangling_target, target)) {
1211 mixed_target = true;
1212 }
1213 if (starts_with(subject, "amend! "))
1214 last_amend = todo.items[i].commit;
1215 }
1216 free(subject);
1217 repo_unuse_commit_buffer(repo, todo.items[i].commit, message);
1218 }
1219
1220 all_fixups_one_target = nr_dangling == todo.nr && !mixed_target;
1221 if (nr_dangling && !all_fixups_one_target) {
1222 ret = error(_("cannot squash '%s': its target is not in the "
1223 "range"), dangling_subject);
1224 } else {
1225 if (last_amend)
1226 *msg_source = last_amend;
1227 ret = 0;
1228 }
1229
1230 out:
1231 free(dangling_subject);
1232 free(dangling_target);
1233 todo_list_release(&todo);
1234 replay_opts_release(&opts);
1235 reset_revision_walk();
1236 release_revisions(&revs);
1237 strvec_clear(&args);
1238 return ret;
1239 }
1240
1241 struct interior_ref_cb {
1242 const struct oidset *interior;
1243 const char *name;
1244 };
1245
1246 static int find_interior_ref(const struct reference *ref, void *cb_data)
1247 {
1248 struct interior_ref_cb *data = cb_data;
1249
1250 if (oidset_contains(data->interior, ref->oid)) {
1251 data->name = xstrdup(ref->name);
1252 return 1;
1253 }
1254
1255 return 0;
1256 }
1257
1258 static bool amend_replaces_target(struct todo_list *todo, int target)
1259 {
1260 int i;
1261
1262 for (i = target + 1; i < todo->nr &&
1263 todo->items[i].command != TODO_PICK; i++) {
1264 if (todo->items[i].command == TODO_SQUASH)
1265 return false;
1266 if (todo->items[i].flags & TODO_REPLACE_FIXUP_MSG)
1267 return true;
1268 }
1269 return false;
1270 }
1271
1272 static int build_squash_message(struct repository *repo,
1273 struct commit *base,
1274 struct commit *tip,
1275 struct strbuf *out)
1276 {
1277 struct rev_info revs;
1278 struct commit *commit;
1279 struct strvec args = STRVEC_INIT;
1280 struct todo_list todo = TODO_LIST_INIT;
1281 struct replay_opts opts = REPLAY_OPTS_INIT;
1282 int i, nr_commits, ret;
1283
1284 repo_init_revisions(repo, &revs, NULL);
1285 strvec_push(&args, "ignored");
1286 strvec_push(&args, "--reverse");
1287 strvec_push(&args, "--topo-order");
1288 strvec_pushf(&args, "%s..%s", oid_to_hex(&base->object.oid),
1289 oid_to_hex(&tip->object.oid));
1290 setup_revisions_from_strvec(&args, &revs, NULL);
1291
1292 if (prepare_revision_walk(&revs) < 0) {
1293 ret = error(_("error preparing revisions"));
1294 goto out;
1295 }
1296
1297 while ((commit = get_revision(&revs)))
1298 strbuf_addf(&todo.buf, "pick %s\n",
1299 oid_to_hex(&commit->object.oid));
1300
1301 if (todo_list_parse_insn_buffer(repo, &opts, todo.buf.buf, &todo) < 0 ||
1302 todo_list_rearrange_squash(&todo) < 0) {
1303 ret = error(_("could not prepare the squash message"));
1304 goto out;
1305 }
1306
1307 nr_commits = todo.nr;
1308 for (i = 0; i < nr_commits; i++) {
1309 struct todo_item *item = &todo.items[i];
1310 const char *message, *body;
1311 size_t commented_len;
1312 bool skip, squashing;
1313
1314 squashing = item->command == TODO_SQUASH ||
1315 (item->flags & TODO_REPLACE_FIXUP_MSG);
1316 if (item->command == TODO_PICK)
1317 skip = amend_replaces_target(&todo, i);
1318 else
1319 skip = !squashing;
1320
1321 message = repo_logmsg_reencode(repo, item->commit, NULL, NULL);
1322 find_commit_subject(message, &body);
1323
1324 if (skip)
1325 commented_len = strlen(body);
1326 else if (squashing)
1327 commented_len = squash_subject_comment_len(body, 1);
1328 else
1329 commented_len = 0;
1330
1331 if (!i)
1332 add_squash_combination_header(out, nr_commits);
1333 strbuf_addch(out, '\n');
1334 add_squash_message_header(out, i + 1, skip);
1335 strbuf_addstr(out, "\n\n");
1336 strbuf_add_commented_lines(out, body, commented_len, comment_line_str);
1337 strbuf_addstr(out, body + commented_len);
1338 strbuf_complete_line(out);
1339
1340 repo_unuse_commit_buffer(repo, item->commit, message);
1341 }
1342
1343 ret = 0;
1344
1345 out:
1346 todo_list_release(&todo);
1347 replay_opts_release(&opts);
1348 reset_revision_walk();
1349 release_revisions(&revs);
1350 strvec_clear(&args);
1351 return ret;
1352 }
1353
1354 static int cmd_history_squash(int argc,
1355 const char **argv,
1356 const char *prefix,
1357 struct repository *repo)
1358 {
1359 const char * const usage[] = {
1360 GIT_HISTORY_SQUASH_USAGE,
1361 NULL,
1362 };
1363 enum ref_action action = REF_ACTION_DEFAULT;
1364 enum commit_tree_flags flags = 0;
1365 int dry_run = 0;
1366 struct option options[] = {
1367 OPT_CALLBACK_F(0, "update-refs", &action, "(branches|head)",
1368 N_("control which refs should be updated"),
1369 PARSE_OPT_NONEG, parse_ref_action),
1370 OPT_BOOL('n', "dry-run", &dry_run,
1371 N_("perform a dry-run without updating any refs")),
1372 OPT_BIT(0, "reedit-message", &flags,
1373 N_("open an editor to modify the commit message"),
1374 COMMIT_TREE_EDIT_MESSAGE),
1375 OPT_END(),
1376 };
1377 struct strbuf reflog_msg = STRBUF_INIT;
1378 struct strbuf message = STRBUF_INIT;
1379 struct oidset interior = OIDSET_INIT;
1380 struct commit *base, *oldest, *tip, *rewritten, *msg_source,
1381 *amend_source;
1382 const struct object_id *base_tree_oid, *tip_tree_oid;
1383 const char *message_template = NULL;
1384 struct commit_list *parents = NULL;
1385 struct rev_info revs = { 0 };
1386 int ret;
1387
1388 argc = parse_options(argc, argv, prefix, options, usage,
1389 PARSE_OPT_KEEP_UNKNOWN_OPT);
1390 if (!argc) {
1391 ret = error(_("command expects a revision range"));
1392 goto out;
1393 }
1394 repo_config(repo, git_default_config, NULL);
1395
1396 if (action == REF_ACTION_DEFAULT)
1397 action = REF_ACTION_BRANCHES;
1398
1399 ret = resolve_squash_range(repo, argv, &base, &oldest, &tip,
1400 &interior);
1401 if (ret < 0)
1402 goto out;
1403
1404 ret = reject_dangling_fixups(repo, base, tip, oldest, &msg_source,
1405 &amend_source);
1406 if (ret < 0)
1407 goto out;
1408 if (amend_source) {
1409 const char *amend_message, *body;
1410
1411 amend_message = repo_logmsg_reencode(repo, amend_source,
1412 NULL, NULL);
1413 find_commit_subject(amend_message, &body);
1414 body = skip_blank_lines(body + commit_subject_length(body));
1415 strbuf_addstr(&message, body);
1416 message_template = message.buf;
1417 repo_unuse_commit_buffer(repo, amend_source, amend_message);
1418 }
1419
1420 if (action == REF_ACTION_BRANCHES) {
1421 struct interior_ref_cb cb = { .interior = &interior };
1422
1423 refs_for_each_ref(get_main_ref_store(repo),
1424 find_interior_ref, &cb);
1425 if (cb.name) {
1426 ret = error(_("'%s' points into the squashed range"),
1427 cb.name);
1428 advise_if_enabled(ADVICE_HISTORY_UPDATE_REFS,
1429 _("Use --update-refs=head to rewrite only "
1430 "the current branch and leave such refs "
1431 "untouched."));
1432 free((char *)cb.name);
1433 goto out;
1434 }
1435 }
1436
1437 if (flags & COMMIT_TREE_EDIT_MESSAGE) {
1438 strbuf_reset(&message);
1439 ret = build_squash_message(repo, base, tip, &message);
1440 if (ret < 0)
1441 goto out;
1442 message_template = message.buf;
1443 }
1444
1445 ret = setup_revwalk(repo, action, tip, &revs);
1446 if (ret < 0)
1447 goto out;
1448
1449 base_tree_oid = &repo_get_commit_tree(repo, base)->object.oid;
1450 tip_tree_oid = &repo_get_commit_tree(repo, tip)->object.oid;
1451 commit_list_append(base, &parents);
1452
1453 ret = commit_tree_ext(repo, "squash", msg_source, message_template,
1454 parents,
1455 base_tree_oid, tip_tree_oid, &rewritten, flags);
1456 if (ret < 0) {
1457 ret = error(_("failed writing squashed commit"));
1458 goto out;
1459 }
1460
1461 strbuf_addstr(&reflog_msg, "squash: updating ");
1462 strbuf_join_argv(&reflog_msg, argc, argv, ' ');
1463
1464 ret = handle_reference_updates(&revs, action, tip, rewritten,
1465 reflog_msg.buf, dry_run,
1466 REPLAY_EMPTY_COMMIT_ABORT);
1467 if (ret < 0) {
1468 ret = error(_("failed replaying descendants"));
1469 goto out;
1470 }
1471
1472 ret = 0;
1473
1474 out:
1475 strbuf_release(&reflog_msg);
1476 strbuf_release(&message);
1477 oidset_clear(&interior);
1478 commit_list_free(parents);
1479 release_revisions(&revs);
1480 return ret;
1481 }
1482
1483 static int update_worktree(struct repository *repo,
1484 const struct commit *old_head,
1485 const struct commit *new_head,
1486 bool dry_run)
1487 {
1488 struct reset_working_tree_options opts = {
1489 .oid_from = &old_head->object.oid,
1490 .oid = &new_head->object.oid,
1491 };
1492 if (dry_run)
1493 opts.flags |= RESET_WORKING_TREE_DRY_RUN;
1494 return reset_working_tree(repo, &opts);
1495 }
1496
1497 static int find_head_tree_change(struct repository *repo,
1498 const struct replay_result *result,
1499 struct commit **old_head,
1500 struct commit **new_head,
1501 bool *changed)
1502 {
1503 const struct replay_ref_update *head_update = NULL;
1504 struct commit *old_head_commit, *new_head_commit;
1505 struct tree *old_head_tree, *new_head_tree;
1506 const char *head_target;
1507 int head_flags;
1508
1509 *changed = false;
1510
1511 head_target = refs_resolve_ref_unsafe(get_main_ref_store(repo), "HEAD",
1512 RESOLVE_REF_NO_RECURSE | RESOLVE_REF_READING,
1513 NULL, &head_flags);
1514 if (!head_target)
1515 return error(_("cannot look up HEAD"));
1516
1517 for (size_t i = 0; i < result->updates_nr; i++) {
1518 if (!strcmp(result->updates[i].refname, head_target)) {
1519 head_update = &result->updates[i];
1520 break;
1521 }
1522 }
1523
1524 if (!head_update)
1525 return 0;
1526
1527 old_head_commit = lookup_commit_reference(repo, &head_update->old_oid);
1528 new_head_commit = lookup_commit_reference(repo, &head_update->new_oid);
1529 if (!old_head_commit || !new_head_commit)
1530 return error(_("cannot resolve HEAD commit"));
1531
1532 old_head_tree = repo_get_commit_tree(repo, old_head_commit);
1533 new_head_tree = repo_get_commit_tree(repo, new_head_commit);
1534 if (!old_head_tree || !new_head_tree)
1535 return error(_("cannot resolve tree for HEAD"));
1536
1537 if (oideq(&old_head_tree->object.oid, &new_head_tree->object.oid))
1538 return 0;
1539
1540 *old_head = old_head_commit;
1541 *new_head = new_head_commit;
1542 *changed = true;
1543
1544 return 0;
1545 }
1546
1547 static int cmd_history_drop(int argc,
1548 const char **argv,
1549 const char *prefix,
1550 struct repository *repo)
1551 {
1552 const char * const usage[] = {
1553 GIT_HISTORY_DROP_USAGE,
1554 NULL,
1555 };
1556 enum replay_empty_commit_action empty = REPLAY_EMPTY_COMMIT_DROP;
1557 enum ref_action action = REF_ACTION_DEFAULT;
1558 int dry_run = 0;
1559 struct option options[] = {
1560 OPT_CALLBACK_F(0, "update-refs", &action, "(branches|head)",
1561 N_("control which refs should be updated"),
1562 PARSE_OPT_NONEG, parse_ref_action),
1563 OPT_BOOL('n', "dry-run", &dry_run,
1564 N_("perform a dry-run without updating any refs")),
1565 OPT_CALLBACK_F(0, "empty", &empty, "(drop|keep|abort)",
1566 N_("how to handle descendants that become empty"),
1567 PARSE_OPT_NONEG, parse_opt_empty),
1568 OPT_END(),
1569 };
1570 struct strbuf reflog_msg = STRBUF_INIT;
1571 struct commit *original, *rewritten;
1572 struct rev_info revs = { 0 };
1573 struct replay_result result = { 0 };
1574 struct commit *old_head, *new_head;
1575 bool head_moves = false;
1576 int ret;
1577
1578 argc = parse_options(argc, argv, prefix, options, usage, 0);
1579 if (argc != 1) {
1580 ret = error(_("command expects a single revision"));
1581 goto out;
1582 }
1583 repo_config(repo, git_default_config, NULL);
1584
1585 if (action == REF_ACTION_DEFAULT)
1586 action = REF_ACTION_BRANCHES;
1587
1588 original = lookup_commit_reference_by_name(argv[0]);
1589 if (!original) {
1590 ret = error(_("commit cannot be found: %s"), argv[0]);
1591 goto out;
1592 }
1593
1594 if (!original->parents) {
1595 ret = error(_("cannot drop root commit %s: "
1596 "it has no parent to replay onto"),
1597 argv[0]);
1598 goto out;
1599 } else if (original->parents->next) {
1600 ret = error(_("cannot drop merge commit: %s"), argv[0]);
1601 goto out;
1602 }
1603
1604 ret = setup_revwalk(repo, action, original, &revs);
1605 if (ret)
1606 goto out;
1607
1608 rewritten = original->parents->item;
1609
1610 ret = compute_pending_ref_updates(&revs, action, original, rewritten,
1611 empty, &result);
1612 if (ret) {
1613 ret = error(_("failed replaying descendants"));
1614 goto out;
1615 }
1616
1617 /*
1618 * If HEAD will move as a result of the rewrite then we'll have to
1619 * merge in the changes into the worktree and index. This merge can of
1620 * course conflict, which will cause the whole operation to abort.
1621 *
1622 * If we had already updated the refs at that point then we'd have an
1623 * inconsistent repository state. So we first perform a dry-run merge
1624 * here before updating refs.
1625 */
1626 if (!is_bare_repository(repo)) {
1627 ret = find_head_tree_change(repo, &result, &old_head,
1628 &new_head, &head_moves);
1629 if (ret < 0)
1630 goto out;
1631
1632 if (head_moves && update_worktree(repo, old_head, new_head, true) < 0) {
1633 ret = error(_("dropping this commit would "
1634 "overwrite local changes; aborting"));
1635 goto out;
1636 }
1637 }
1638
1639 strbuf_addf(&reflog_msg, "drop: dropping %s", argv[0]);
1640 ret = apply_pending_ref_updates(repo, &result, reflog_msg.buf, dry_run);
1641 if (ret < 0) {
1642 ret = error(_("failed to update references"));
1643 goto out;
1644 }
1645
1646 if (!dry_run && head_moves && update_worktree(repo, old_head, new_head, false) < 0) {
1647 ret = error(_("could not update working tree to new commit %s"),
1648 oid_to_hex(&new_head->object.oid));
1649 goto out;
1650 }
1651
1652 ret = 0;
1653
1654 out:
1655 replay_result_release(&result);
1656 strbuf_release(&reflog_msg);
1657 release_revisions(&revs);
1658 return ret;
1659 }
1660
1661 int cmd_history(int argc,
1662 const char **argv,
1663 const char *prefix,
1664 struct repository *repo)
1665 {
1666 const char * const usage[] = {
1667 GIT_HISTORY_DROP_USAGE,
1668 GIT_HISTORY_FIXUP_USAGE,
1669 GIT_HISTORY_REWORD_USAGE,
1670 GIT_HISTORY_SPLIT_USAGE,
1671 GIT_HISTORY_SQUASH_USAGE,
1672 NULL,
1673 };
1674 parse_opt_subcommand_fn *fn = NULL;
1675 struct option options[] = {
1676 OPT_SUBCOMMAND("drop", &fn, cmd_history_drop),
1677 OPT_SUBCOMMAND("fixup", &fn, cmd_history_fixup),
1678 OPT_SUBCOMMAND("reword", &fn, cmd_history_reword),
1679 OPT_SUBCOMMAND("split", &fn, cmd_history_split),
1680 OPT_SUBCOMMAND("squash", &fn, cmd_history_squash),
1681 OPT_END(),
1682 };
1683
1684 argc = parse_options(argc, argv, prefix, options, usage, 0);
1685 return fn(argc, argv, prefix, repo);
1686 }