at commit a0189536

1 #define USE_THE_REPOSITORY_VARIABLE
2
3 #include "builtin.h"
4 #include "cache-tree.h"
5 #include "commit.h"
6 #include "commit-reach.h"
7 #include "config.h"
8 #include "editor.h"
9 #include "environment.h"
10 #include "gettext.h"
11 #include "hex.h"
12 #include "lockfile.h"
13 #include "merge-ort.h"
14 #include "oidmap.h"
15 #include "parse-options.h"
16 #include "path.h"
17 #include "read-cache.h"
18 #include "refs.h"
19 #include "replay.h"
20 #include "reset.h"
21 #include "revision.h"
22 #include "sequencer.h"
23 #include "strvec.h"
24 #include "tree.h"
25 #include "tree-walk.h"
26 #include "unpack-trees.h"
27 #include "wt-status.h"
28
29 #define GIT_HISTORY_DROP_USAGE \
30 N_("git history drop <commit> [--dry-run] [--update-refs=(branches|head)] [--empty=(drop|keep|abort)]")
31 #define GIT_HISTORY_FIXUP_USAGE \
32 N_("git history fixup <commit> [--dry-run] [--update-refs=(branches|head)] [--reedit-message] [--empty=(drop|keep|abort)]")
33 #define GIT_HISTORY_REWORD_USAGE \
34 N_("git history reword <commit> [--dry-run] [--update-refs=(branches|head)]")
35 #define GIT_HISTORY_SPLIT_USAGE \
36 N_("git history split <commit> [--dry-run] [--update-refs=(branches|head)] [--] [<pathspec>...]")
37
38 static void change_data_free(void *util, const char *str UNUSED)
39 {
40 struct wt_status_change_data *d = util;
41 free(d->rename_source);
42 free(d);
43 }
44
45 static int fill_commit_message(struct repository *repo,
46 const struct object_id *old_tree,
47 const struct object_id *new_tree,
48 const char *default_message,
49 const char *action,
50 struct strbuf *out)
51 {
52 const char *path = git_path_commit_editmsg();
53 const char *hint =
54 _("Please enter the commit message for the %s changes."
55 " Lines starting\nwith '%s' will be ignored, and an"
56 " empty message aborts the commit.\n");
57 struct wt_status s;
58
59 wt_status_prepare(repo, &s);
60 FREE_AND_NULL(s.branch);
61 s.ahead_behind_flags = AHEAD_BEHIND_QUICK;
62 s.commit_template = 1;
63 s.colopts = 0;
64 s.display_comment_prefix = 1;
65 s.hints = 0;
66 s.use_color = 0;
67 s.whence = FROM_COMMIT;
68 s.committable = 1;
69
70 s.fp = fopen(path, "w");
71 if (!s.fp)
72 return error_errno(_("could not open '%s'"), path);
73
74 strbuf_addstr(out, default_message);
75 strbuf_addch(out, '\n');
76 strbuf_commented_addf(out, comment_line_str, hint, action, comment_line_str);
77 if (fwrite(out->buf, 1, out->len, s.fp) != out->len)
78 die_errno(_("could not write to '%s'"), path);
79
80 wt_status_collect_changes_trees(&s, old_tree, new_tree);
81 wt_status_print(&s);
82 wt_status_collect_free_buffers(&s);
83 string_list_clear_func(&s.change, change_data_free);
84 if (fclose(s.fp))
85 die_errno(_("could not write to '%s'"), path);
86
87 strbuf_reset(out);
88 if (launch_editor(path, out, NULL)) {
89 fprintf(stderr, _("Aborting commit as launching the editor failed.\n"));
90 return -1;
91 }
92 strbuf_stripspace(out, comment_line_str);
93
94 cleanup_message(out, COMMIT_MSG_CLEANUP_ALL, 0);
95
96 if (!out->len) {
97 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
98 return -1;
99 }
100
101 return 0;
102 }
103
104 enum commit_tree_flags {
105 COMMIT_TREE_EDIT_MESSAGE = (1 << 0),
106 };
107
108 static int commit_tree_ext(struct repository *repo,
109 const char *action,
110 struct commit *commit_with_message,
111 const struct commit_list *parents,
112 const struct object_id *old_tree,
113 const struct object_id *new_tree,
114 struct commit **out,
115 enum commit_tree_flags flags)
116 {
117 const char *exclude_gpgsig[] = {
118 /* We reencode the message, so the encoding needs to be stripped. */
119 "encoding",
120 /* We need to strip signatures as those will become invalid. */
121 "gpgsig",
122 "gpgsig-sha256",
123 NULL,
124 };
125 const char *original_message, *original_body, *ptr;
126 struct commit_extra_header *original_extra_headers = NULL;
127 struct strbuf commit_message = STRBUF_INIT;
128 struct object_id rewritten_commit_oid;
129 char *original_author = NULL;
130 size_t len;
131 int ret;
132
133 /* We retain authorship of the original commit. */
134 original_message = repo_logmsg_reencode(repo, commit_with_message, NULL, NULL);
135 ptr = find_commit_header(original_message, "author", &len);
136 if (ptr)
137 original_author = xmemdupz(ptr, len);
138 find_commit_subject(original_message, &original_body);
139
140 if (flags & COMMIT_TREE_EDIT_MESSAGE) {
141 ret = fill_commit_message(repo, old_tree, new_tree,
142 original_body, action, &commit_message);
143 if (ret < 0)
144 goto out;
145 } else {
146 strbuf_addstr(&commit_message, original_body);
147 }
148
149 original_extra_headers = read_commit_extra_headers(commit_with_message,
150 exclude_gpgsig);
151
152 ret = commit_tree_extended(commit_message.buf, commit_message.len, new_tree,
153 parents, &rewritten_commit_oid, original_author,
154 NULL, NULL, original_extra_headers);
155 if (ret < 0)
156 goto out;
157
158 *out = lookup_commit_or_die(&rewritten_commit_oid, "rewritten commit");
159
160 out:
161 free_commit_extra_headers(original_extra_headers);
162 strbuf_release(&commit_message);
163 free(original_author);
164 repo_unuse_commit_buffer(repo, commit_with_message, original_message);
165 return ret;
166 }
167
168 static int commit_tree_with_edited_message(struct repository *repo,
169 const char *action,
170 struct commit *original,
171 struct commit **out)
172 {
173 struct object_id parent_tree_oid;
174 const struct object_id *tree_oid;
175 struct commit *parent;
176
177 tree_oid = &repo_get_commit_tree(repo, original)->object.oid;
178
179 parent = original->parents ? original->parents->item : NULL;
180 if (parent) {
181 if (repo_parse_commit(repo, parent)) {
182 return error(_("unable to parse parent commit %s"),
183 oid_to_hex(&parent->object.oid));
184 }
185
186 parent_tree_oid = repo_get_commit_tree(repo, parent)->object.oid;
187 } else {
188 oidcpy(&parent_tree_oid, repo->hash_algo->empty_tree);
189 }
190
191 return commit_tree_ext(repo, action, original, original->parents,
192 &parent_tree_oid, tree_oid, out, COMMIT_TREE_EDIT_MESSAGE);
193 }
194
195 enum ref_action {
196 REF_ACTION_DEFAULT,
197 REF_ACTION_BRANCHES,
198 REF_ACTION_HEAD,
199 };
200
201 static int parse_ref_action(const struct option *opt, const char *value, int unset)
202 {
203 enum ref_action *action = opt->value;
204
205 BUG_ON_OPT_NEG_NOARG(unset, value);
206 if (!strcmp(value, "branches")) {
207 *action = REF_ACTION_BRANCHES;
208 } else if (!strcmp(value, "head")) {
209 *action = REF_ACTION_HEAD;
210 } else {
211 return error(_("%s expects one of 'branches' or 'head'"),
212 opt->long_name);
213 }
214
215 return 0;
216 }
217
218 static int revwalk_contains_merges(struct repository *repo,
219 const struct strvec *revwalk_args)
220 {
221 struct strvec args = STRVEC_INIT;
222 struct rev_info revs;
223 int ret;
224
225 strvec_pushv(&args, revwalk_args->v);
226 strvec_push(&args, "--min-parents=2");
227
228 repo_init_revisions(repo, &revs, NULL);
229
230 setup_revisions_from_strvec(&args, &revs, NULL);
231 if (args.nr != 1)
232 BUG("revisions were set up with invalid argument");
233
234 if (prepare_revision_walk(&revs) < 0) {
235 ret = error(_("error preparing revisions"));
236 goto out;
237 }
238
239 if (get_revision(&revs)) {
240 ret = error(_("replaying merge commits is not supported yet!"));
241 goto out;
242 }
243
244 reset_revision_walk();
245 ret = 0;
246
247 out:
248 release_revisions(&revs);
249 strvec_clear(&args);
250 return ret;
251 }
252
253 static int setup_revwalk(struct repository *repo,
254 enum ref_action action,
255 struct commit *original,
256 struct rev_info *revs)
257 {
258 struct strvec args = STRVEC_INIT;
259 int ret;
260
261 repo_init_revisions(repo, revs, NULL);
262 strvec_push(&args, "ignored");
263 strvec_push(&args, "--reverse");
264 strvec_push(&args, "--topo-order");
265 strvec_push(&args, "--full-history");
266
267 /* We only want to see commits that are descendants of the old commit. */
268 strvec_pushf(&args, "--ancestry-path=%s",
269 oid_to_hex(&original->object.oid));
270
271 /*
272 * Ancestry path may also show ancestors of the old commit, but we
273 * don't want to see those, either.
274 */
275 strvec_pushf(&args, "^%s", oid_to_hex(&original->object.oid));
276
277 /*
278 * When we're asked to update HEAD we need to verify that the commit
279 * that we want to rewrite is actually an ancestor of it and, if so,
280 * update it. Otherwise we'll update (or print) all descendant
281 * branches.
282 */
283 if (action == REF_ACTION_HEAD) {
284 struct commit_list *from_list = NULL;
285 struct commit *head;
286
287 head = lookup_commit_reference_by_name("HEAD");
288 if (!head) {
289 ret = error(_("cannot look up HEAD"));
290 goto out;
291 }
292
293 commit_list_insert(original, &from_list);
294 ret = repo_is_descendant_of(repo, head, from_list);
295 commit_list_free(from_list);
296
297 if (ret < 0) {
298 ret = error(_("cannot determine descendance"));
299 goto out;
300 } else if (!ret) {
301 ret = error(_("rewritten commit must be an ancestor "
302 "of HEAD when using --update-refs=head"));
303 goto out;
304 }
305
306 strvec_push(&args, "HEAD");
307 } else {
308 strvec_push(&args, "--branches");
309 strvec_push(&args, "HEAD");
310 }
311
312 ret = revwalk_contains_merges(repo, &args);
313 if (ret < 0)
314 goto out;
315
316 setup_revisions_from_strvec(&args, revs, NULL);
317 if (args.nr != 1)
318 BUG("revisions were set up with invalid argument");
319
320 ret = 0;
321
322 out:
323 strvec_clear(&args);
324 return ret;
325 }
326
327 static int handle_ref_update(struct ref_transaction *transaction,
328 const char *refname,
329 const struct object_id *new_oid,
330 const struct object_id *old_oid,
331 const char *reflog_msg,
332 struct strbuf *err)
333 {
334 if (!transaction) {
335 printf("update %s %s %s\n",
336 refname, oid_to_hex(new_oid), oid_to_hex(old_oid));
337 return 0;
338 }
339
340 return ref_transaction_update(transaction, refname, new_oid, old_oid,
341 NULL, NULL, 0, reflog_msg, err);
342 }
343
344 static int compute_pending_ref_updates(struct rev_info *revs,
345 enum ref_action action,
346 struct commit *original,
347 struct commit *rewritten,
348 enum replay_empty_commit_action empty,
349 struct replay_result *result)
350 {
351 const struct name_decoration *decoration;
352 struct replay_revisions_options opts = {
353 .empty = empty,
354 };
355 char hex[GIT_MAX_HEXSZ + 1];
356 bool detached_head;
357 int head_flags = 0;
358 int ret;
359
360 refs_read_ref_full(get_main_ref_store(revs->repo), "HEAD",
361 RESOLVE_REF_NO_RECURSE, NULL, &head_flags);
362 detached_head = !(head_flags & REF_ISSYMREF);
363
364 opts.onto = oid_to_hex_r(hex, &rewritten->object.oid);
365
366 ret = replay_revisions(revs, &opts, result);
367 if (ret)
368 return ret;
369
370 if (action != REF_ACTION_BRANCHES && action != REF_ACTION_HEAD)
371 BUG("unsupported ref action %d", action);
372
373 /*
374 * `replay_revisions()` only updates references that are
375 * ancestors of `rewritten`, so we need to manually
376 * handle updating references that point to `original`.
377 */
378 for (decoration = get_name_decoration(&original->object);
379 decoration;
380 decoration = decoration->next)
381 {
382 if (decoration->type != DECORATION_REF_LOCAL &&
383 decoration->type != DECORATION_REF_HEAD)
384 continue;
385
386 if (action == REF_ACTION_HEAD &&
387 decoration->type != DECORATION_REF_HEAD)
388 continue;
389
390 /*
391 * We only need to update HEAD separately in case it's
392 * detached. If it's not we'd already update the branch
393 * it is pointing to.
394 */
395 if (action == REF_ACTION_BRANCHES &&
396 decoration->type == DECORATION_REF_HEAD &&
397 !detached_head)
398 continue;
399
400 replay_result_queue_update(result, decoration->name,
401 &original->object.oid,
402 &rewritten->object.oid);
403 }
404
405 return 0;
406 }
407
408 static int apply_pending_ref_updates(struct repository *repo,
409 const struct replay_result *result,
410 const char *reflog_msg,
411 int dry_run)
412 {
413 struct ref_transaction *transaction = NULL;
414 struct strbuf err = STRBUF_INIT;
415 int ret;
416
417 if (!dry_run) {
418 transaction = ref_store_transaction_begin(get_main_ref_store(repo),
419 0, &err);
420 if (!transaction) {
421 ret = error(_("failed to begin ref transaction: %s"), err.buf);
422 goto out;
423 }
424 }
425
426 for (size_t i = 0; i < result->updates_nr; i++) {
427 ret = handle_ref_update(transaction,
428 result->updates[i].refname,
429 &result->updates[i].new_oid,
430 &result->updates[i].old_oid,
431 reflog_msg, &err);
432 if (ret) {
433 ret = error(_("failed to update ref '%s': %s"),
434 result->updates[i].refname, err.buf);
435 goto out;
436 }
437 }
438
439 if (transaction && ref_transaction_commit(transaction, &err)) {
440 ret = error(_("failed to commit ref transaction: %s"), err.buf);
441 goto out;
442 }
443
444 ret = 0;
445
446 out:
447 ref_transaction_free(transaction);
448 strbuf_release(&err);
449 return ret;
450 }
451
452 static int handle_reference_updates(struct rev_info *revs,
453 enum ref_action action,
454 struct commit *original,
455 struct commit *rewritten,
456 const char *reflog_msg,
457 int dry_run,
458 enum replay_empty_commit_action empty)
459 {
460 struct replay_result result = { 0 };
461 int ret;
462
463 ret = compute_pending_ref_updates(revs, action, original, rewritten,
464 empty, &result);
465 if (ret)
466 goto out;
467
468 ret = apply_pending_ref_updates(revs->repo, &result, reflog_msg, dry_run);
469
470 out:
471 replay_result_release(&result);
472 return ret;
473 }
474
475 static int commit_became_empty(struct repository *repo,
476 struct commit *original,
477 struct tree *result)
478 {
479 struct commit *parent = original->parents ? original->parents->item : NULL;
480 struct object_id parent_tree_oid;
481
482 if (parent) {
483 if (repo_parse_commit(repo, parent))
484 return error(_("unable to parse parent of %s"),
485 oid_to_hex(&original->object.oid));
486
487 parent_tree_oid = repo_get_commit_tree(repo, parent)->object.oid;
488 } else {
489 oidcpy(&parent_tree_oid, repo->hash_algo->empty_tree);
490 }
491
492 return oideq(&result->object.oid, &parent_tree_oid);
493 }
494
495 static int parse_opt_empty(const struct option *opt, const char *arg, int unset)
496 {
497 enum replay_empty_commit_action *value = opt->value;
498
499 BUG_ON_OPT_NEG(unset);
500
501 if (!strcmp(arg, "drop"))
502 *value = REPLAY_EMPTY_COMMIT_DROP;
503 else if (!strcmp(arg, "keep"))
504 *value = REPLAY_EMPTY_COMMIT_KEEP;
505 else if (!strcmp(arg, "abort"))
506 *value = REPLAY_EMPTY_COMMIT_ABORT;
507 else
508 die(_("unrecognized '--empty=' action '%s'; "
509 "valid values are \"drop\", \"keep\", and \"abort\"."), arg);
510
511 return 0;
512 }
513
514 static int cmd_history_fixup(int argc,
515 const char **argv,
516 const char *prefix,
517 struct repository *repo)
518 {
519 const char * const usage[] = {
520 GIT_HISTORY_FIXUP_USAGE,
521 NULL,
522 };
523 enum replay_empty_commit_action empty = REPLAY_EMPTY_COMMIT_DROP;
524 enum ref_action action = REF_ACTION_DEFAULT;
525 enum commit_tree_flags flags = 0;
526 int dry_run = 0;
527 struct option options[] = {
528 OPT_CALLBACK_F(0, "update-refs", &action, "(branches|head)",
529 N_("control which refs should be updated"),
530 PARSE_OPT_NONEG, parse_ref_action),
531 OPT_BOOL('n', "dry-run", &dry_run,
532 N_("perform a dry-run without updating any refs")),
533 OPT_BIT(0, "reedit-message", &flags,
534 N_("open an editor to modify the commit message"),
535 COMMIT_TREE_EDIT_MESSAGE),
536 OPT_CALLBACK_F(0, "empty", &empty, "(drop|keep|abort)",
537 N_("how to handle commits that become empty"),
538 PARSE_OPT_NONEG, parse_opt_empty),
539 OPT_END(),
540 };
541 struct merge_result merge_result = { 0 };
542 struct merge_options merge_opts = { 0 };
543 struct strbuf reflog_msg = STRBUF_INIT;
544 struct commit *head_commit, *original, *rewritten;
545 struct tree *head_tree, *original_tree, *index_tree;
546 struct rev_info revs = { 0 };
547 bool skip_commit = false;
548 int ret;
549
550 argc = parse_options(argc, argv, prefix, options, usage, 0);
551 if (argc != 1) {
552 ret = error(_("command expects a single revision"));
553 goto out;
554 }
555 repo_config(repo, git_default_config, NULL);
556
557 if (action == REF_ACTION_DEFAULT)
558 action = REF_ACTION_BRANCHES;
559
560 if (is_bare_repository(repo)) {
561 ret = error(_("cannot run fixup in a bare repository"));
562 goto out;
563 }
564
565 /* Resolve the original commit, which is the one we want to fix up. */
566 original = lookup_commit_reference_by_name(argv[0]);
567 if (!original) {
568 ret = error(_("commit cannot be found: %s"), argv[0]);
569 goto out;
570 }
571
572 /*
573 * Resolve HEAD so we can use its tree as the merge base: the staged
574 * changes are expressed as a diff from HEAD's tree to the index tree.
575 */
576 head_commit = lookup_commit_reference_by_name("HEAD");
577 if (!head_commit) {
578 ret = error(_("cannot look up HEAD"));
579 goto out;
580 }
581
582 head_tree = repo_get_commit_tree(repo, head_commit);
583 if (!head_tree) {
584 ret = error(_("cannot get tree for HEAD"));
585 goto out;
586 }
587
588 if (repo_read_index(repo) < 0) {
589 ret = error(_("unable to read index"));
590 goto out;
591 }
592
593 if (!repo_index_has_changes(repo, head_tree, NULL)) {
594 ret = error(_("nothing to fixup: no staged changes"));
595 goto out;
596 }
597
598 /*
599 * Write the index as a tree object. This is the "theirs" side of the
600 * three-way merge: it is HEAD's tree with the staged changes applied.
601 */
602 index_tree = write_in_core_index_as_tree(repo, repo->index);
603 if (!index_tree) {
604 ret = error(_("unable to write index as a tree"));
605 goto out;
606 }
607
608 original_tree = repo_get_commit_tree(repo, original);
609 if (!original_tree) {
610 ret = error(_("cannot get tree for commit %s"), argv[0]);
611 goto out;
612 }
613
614 /*
615 * Perform the three-way merge to reapply changes in the index onto the
616 * target commit. This is using basically the same logic as a
617 * cherry-pick, where the base commit is our HEAD, ours is the original
618 * tree and theirs is the index tree.
619 */
620 init_basic_merge_options(&merge_opts, repo);
621 merge_opts.ancestor = "HEAD";
622 merge_opts.branch1 = argv[0];
623 merge_opts.branch2 = "staged";
624 merge_incore_nonrecursive(&merge_opts, head_tree,
625 original_tree, index_tree, &merge_result);
626
627 if (merge_result.clean < 0) {
628 ret = error(_("merge failed while applying fixup"));
629 goto out;
630 }
631
632 if (!merge_result.clean) {
633 ret = error(_("fixup would produce conflicts; aborting"));
634 goto out;
635 }
636
637 ret = commit_became_empty(repo, original, merge_result.tree);
638 if (ret < 0)
639 goto out;
640 if (ret > 0) {
641 switch (empty) {
642 case REPLAY_EMPTY_COMMIT_DROP:
643 /*
644 * Drop the target commit by replaying its descendants
645 * directly onto its parent.
646 */
647 rewritten = original->parents ? original->parents->item : NULL;
648
649 /*
650 * TODO: we don't yet have the ability to drop root
651 * commits, but there's ultimately no good reason for
652 * this restriction to exist other than a technical
653 * limitation.
654 */
655 if (!rewritten) {
656 ret = error(_("cannot drop root commit %s: "
657 "it has no parent to replay onto"),
658 argv[0]);
659 goto out;
660 }
661
662 skip_commit = true;
663 break;
664 case REPLAY_EMPTY_COMMIT_KEEP:
665 /* Proceed and record the empty commit. */
666 break;
667 case REPLAY_EMPTY_COMMIT_ABORT:
668 ret = error(_("fixup makes commit %s empty"), argv[0]);
669 goto out;
670 }
671 }
672
673 ret = setup_revwalk(repo, action, original, &revs);
674 if (ret)
675 goto out;
676
677 if (!skip_commit) {
678 ret = commit_tree_ext(repo, "fixup", original, original->parents,
679 &original_tree->object.oid, &merge_result.tree->object.oid,
680 &rewritten, flags);
681 if (ret < 0) {
682 ret = error(_("failed writing fixed-up commit"));
683 goto out;
684 }
685 }
686
687 strbuf_addf(&reflog_msg, "fixup: updating %s", argv[0]);
688
689 ret = handle_reference_updates(&revs, action, original, rewritten,
690 reflog_msg.buf, dry_run, empty);
691 if (ret < 0) {
692 ret = error(_("failed replaying descendants"));
693 goto out;
694 }
695
696 ret = 0;
697
698 out:
699 merge_finalize(&merge_opts, &merge_result);
700 strbuf_release(&reflog_msg);
701 release_revisions(&revs);
702 return ret;
703 }
704
705 static int cmd_history_reword(int argc,
706 const char **argv,
707 const char *prefix,
708 struct repository *repo)
709 {
710 const char * const usage[] = {
711 GIT_HISTORY_REWORD_USAGE,
712 NULL,
713 };
714 enum ref_action action = REF_ACTION_DEFAULT;
715 int dry_run = 0;
716 struct option options[] = {
717 OPT_CALLBACK_F(0, "update-refs", &action, "(branches|head)",
718 N_("control which refs should be updated"),
719 PARSE_OPT_NONEG, parse_ref_action),
720 OPT_BOOL('n', "dry-run", &dry_run,
721 N_("perform a dry-run without updating any refs")),
722 OPT_END(),
723 };
724 struct strbuf reflog_msg = STRBUF_INIT;
725 struct commit *original, *rewritten;
726 struct rev_info revs = { 0 };
727 int ret;
728
729 argc = parse_options(argc, argv, prefix, options, usage, 0);
730 if (argc != 1) {
731 ret = error(_("command expects a single revision"));
732 goto out;
733 }
734 repo_config(repo, git_default_config, NULL);
735
736 if (action == REF_ACTION_DEFAULT)
737 action = REF_ACTION_BRANCHES;
738
739 original = lookup_commit_reference_by_name(argv[0]);
740 if (!original) {
741 ret = error(_("commit cannot be found: %s"), argv[0]);
742 goto out;
743 }
744
745 ret = setup_revwalk(repo, action, original, &revs);
746 if (ret)
747 goto out;
748
749 ret = commit_tree_with_edited_message(repo, "reworded", original, &rewritten);
750 if (ret < 0) {
751 ret = error(_("failed writing reworded commit"));
752 goto out;
753 }
754
755 strbuf_addf(&reflog_msg, "reword: updating %s", argv[0]);
756
757 ret = handle_reference_updates(&revs, action, original, rewritten,
758 reflog_msg.buf, dry_run, REPLAY_EMPTY_COMMIT_ABORT);
759 if (ret < 0) {
760 ret = error(_("failed replaying descendants"));
761 goto out;
762 }
763
764 ret = 0;
765
766 out:
767 strbuf_release(&reflog_msg);
768 release_revisions(&revs);
769 return ret;
770 }
771
772 static int write_ondisk_index(struct repository *repo,
773 struct object_id *oid,
774 const char *path)
775 {
776 struct unpack_trees_options opts = { 0 };
777 struct lock_file lock = LOCK_INIT;
778 struct tree_desc tree_desc;
779 struct index_state index;
780 struct tree *tree;
781 int ret;
782
783 index_state_init(&index, repo);
784
785 opts.head_idx = -1;
786 opts.src_index = &index;
787 opts.dst_index = &index;
788
789 tree = repo_parse_tree_indirect(repo, oid);
790 if (!tree) {
791 ret = error(_("unable to parse tree %s"), oid_to_hex(oid));
792 goto out;
793 }
794 init_tree_desc(&tree_desc, &tree->object.oid, tree->buffer, tree->size);
795
796 if (unpack_trees(1, &tree_desc, &opts)) {
797 ret = error(_("unable to populate index with tree"));
798 goto out;
799 }
800
801 prime_cache_tree(repo, &index, tree);
802
803 if (repo_hold_lock_file_for_update(repo, &lock, path, 0) < 0) {
804 ret = error_errno(_("unable to acquire index lock"));
805 goto out;
806 }
807
808 if (write_locked_index(&index, &lock, COMMIT_LOCK)) {
809 ret = error(_("unable to write new index file"));
810 goto out;
811 }
812
813 ret = 0;
814
815 out:
816 rollback_lock_file(&lock);
817 release_index(&index);
818 return ret;
819 }
820
821 static int split_commit(struct repository *repo,
822 struct commit *original,
823 struct pathspec *pathspec,
824 struct commit **out)
825 {
826 struct interactive_options interactive_opts = INTERACTIVE_OPTIONS_INIT;
827 struct strbuf index_file = STRBUF_INIT;
828 struct index_state index = INDEX_STATE_INIT(repo);
829 const struct object_id *original_commit_tree_oid;
830 const struct object_id *old_tree_oid, *new_tree_oid;
831 struct object_id parent_tree_oid;
832 char original_commit_oid[GIT_MAX_HEXSZ + 1];
833 struct commit *first_commit, *second_commit;
834 struct commit_list *parents = NULL;
835 struct tree *split_tree;
836 int ret;
837
838 if (original->parents) {
839 if (repo_parse_commit(repo, original->parents->item)) {
840 ret = error(_("unable to parse parent commit %s"),
841 oid_to_hex(&original->parents->item->object.oid));
842 goto out;
843 }
844
845 parent_tree_oid = *get_commit_tree_oid(original->parents->item);
846 } else {
847 oidcpy(&parent_tree_oid, repo->hash_algo->empty_tree);
848 }
849 original_commit_tree_oid = get_commit_tree_oid(original);
850
851 /*
852 * Construct the first commit. This is done by taking the original
853 * commit parent's tree and selectively patching changes from the diff
854 * between that parent and its child.
855 */
856 repo_git_path_replace(repo, &index_file, "%s", "history-split.index");
857
858 ret = write_ondisk_index(repo, &parent_tree_oid, index_file.buf);
859 if (ret < 0)
860 goto out;
861
862 ret = read_index_from(&index, index_file.buf, repo->gitdir);
863 if (ret < 0) {
864 ret = error(_("failed reading temporary index"));
865 goto out;
866 }
867
868 oid_to_hex_r(original_commit_oid, &original->object.oid);
869 ret = run_add_p_index(repo, &index, index_file.buf, &interactive_opts,
870 original_commit_oid, pathspec, ADD_P_DISALLOW_EDIT);
871 if (ret < 0)
872 goto out;
873
874 split_tree = write_in_core_index_as_tree(repo, &index);
875 if (!split_tree) {
876 ret = error(_("failed split tree"));
877 goto out;
878 }
879
880 unlink(index_file.buf);
881 strbuf_release(&index_file);
882
883 /*
884 * We disallow the cases where either the split-out commit or the
885 * original commit would become empty. Consequently, if we see that the
886 * new tree ID matches either of those trees we abort.
887 */
888 if (oideq(&split_tree->object.oid, &parent_tree_oid)) {
889 ret = error(_("split commit is empty"));
890 goto out;
891 } else if (oideq(&split_tree->object.oid, original_commit_tree_oid)) {
892 ret = error(_("split commit tree matches original commit"));
893 goto out;
894 }
895
896 /*
897 * The first commit is constructed from the split-out tree. The base
898 * that shall be diffed against is the parent of the original commit.
899 */
900 ret = commit_tree_ext(repo, "split-out", original, original->parents, &parent_tree_oid,
901 &split_tree->object.oid, &first_commit, COMMIT_TREE_EDIT_MESSAGE);
902 if (ret < 0) {
903 ret = error(_("failed writing first commit"));
904 goto out;
905 }
906
907 /*
908 * The second commit is constructed from the original tree. The base to
909 * diff against and the parent in this case is the first split-out
910 * commit.
911 */
912 commit_list_append(first_commit, &parents);
913
914 old_tree_oid = &repo_get_commit_tree(repo, first_commit)->object.oid;
915 new_tree_oid = &repo_get_commit_tree(repo, original)->object.oid;
916
917 ret = commit_tree_ext(repo, "split-out", original, parents, old_tree_oid,
918 new_tree_oid, &second_commit, COMMIT_TREE_EDIT_MESSAGE);
919 if (ret < 0) {
920 ret = error(_("failed writing second commit"));
921 goto out;
922 }
923
924 *out = second_commit;
925 ret = 0;
926
927 out:
928 if (index_file.len)
929 unlink(index_file.buf);
930 strbuf_release(&index_file);
931 commit_list_free(parents);
932 release_index(&index);
933 return ret;
934 }
935
936 static int cmd_history_split(int argc,
937 const char **argv,
938 const char *prefix,
939 struct repository *repo)
940 {
941 const char * const usage[] = {
942 GIT_HISTORY_SPLIT_USAGE,
943 NULL,
944 };
945 enum ref_action action = REF_ACTION_DEFAULT;
946 int dry_run = 0;
947 struct option options[] = {
948 OPT_CALLBACK_F(0, "update-refs", &action, "(branches|head)",
949 N_("control ref update behavior"),
950 PARSE_OPT_NONEG, parse_ref_action),
951 OPT_BOOL('n', "dry-run", &dry_run,
952 N_("perform a dry-run without updating any refs")),
953 OPT_END(),
954 };
955 struct commit *original, *rewritten = NULL;
956 struct strbuf reflog_msg = STRBUF_INIT;
957 struct pathspec pathspec = { 0 };
958 struct rev_info revs = { 0 };
959 int ret;
960
961 argc = parse_options(argc, argv, prefix, options, usage, 0);
962 if (argc < 1) {
963 ret = error(_("command expects a committish"));
964 goto out;
965 }
966 repo_config(repo, git_default_config, NULL);
967
968 if (action == REF_ACTION_DEFAULT)
969 action = REF_ACTION_BRANCHES;
970
971 parse_pathspec(&pathspec, 0,
972 PATHSPEC_PREFER_FULL |
973 PATHSPEC_SYMLINK_LEADING_PATH |
974 PATHSPEC_PREFIX_ORIGIN,
975 prefix, argv + 1);
976
977 original = lookup_commit_reference_by_name(argv[0]);
978 if (!original) {
979 ret = error(_("commit cannot be found: %s"), argv[0]);
980 goto out;
981 }
982
983 ret = setup_revwalk(repo, action, original, &revs);
984 if (ret < 0)
985 goto out;
986
987 if (original->parents && original->parents->next) {
988 ret = error(_("cannot split up merge commit"));
989 goto out;
990 }
991
992 ret = split_commit(repo, original, &pathspec, &rewritten);
993 if (ret < 0)
994 goto out;
995
996 strbuf_addf(&reflog_msg, "split: updating %s", argv[0]);
997
998 ret = handle_reference_updates(&revs, action, original, rewritten,
999 reflog_msg.buf, dry_run, REPLAY_EMPTY_COMMIT_ABORT);
1000 if (ret < 0) {
1001 ret = error(_("failed replaying descendants"));
1002 goto out;
1003 }
1004
1005 ret = 0;
1006
1007 out:
1008 strbuf_release(&reflog_msg);
1009 clear_pathspec(&pathspec);
1010 release_revisions(&revs);
1011 return ret;
1012 }
1013
1014 static int update_worktree(struct repository *repo,
1015 const struct commit *old_head,
1016 const struct commit *new_head,
1017 bool dry_run)
1018 {
1019 struct reset_working_tree_options opts = {
1020 .oid_from = &old_head->object.oid,
1021 .oid = &new_head->object.oid,
1022 };
1023 if (dry_run)
1024 opts.flags |= RESET_WORKING_TREE_DRY_RUN;
1025 return reset_working_tree(repo, &opts);
1026 }
1027
1028 static int find_head_tree_change(struct repository *repo,
1029 const struct replay_result *result,
1030 struct commit **old_head,
1031 struct commit **new_head,
1032 bool *changed)
1033 {
1034 const struct replay_ref_update *head_update = NULL;
1035 struct commit *old_head_commit, *new_head_commit;
1036 struct tree *old_head_tree, *new_head_tree;
1037 const char *head_target;
1038 int head_flags;
1039
1040 *changed = false;
1041
1042 head_target = refs_resolve_ref_unsafe(get_main_ref_store(repo), "HEAD",
1043 RESOLVE_REF_NO_RECURSE | RESOLVE_REF_READING,
1044 NULL, &head_flags);
1045 if (!head_target)
1046 return error(_("cannot look up HEAD"));
1047
1048 for (size_t i = 0; i < result->updates_nr; i++) {
1049 if (!strcmp(result->updates[i].refname, head_target)) {
1050 head_update = &result->updates[i];
1051 break;
1052 }
1053 }
1054
1055 if (!head_update)
1056 return 0;
1057
1058 old_head_commit = lookup_commit_reference(repo, &head_update->old_oid);
1059 new_head_commit = lookup_commit_reference(repo, &head_update->new_oid);
1060 if (!old_head_commit || !new_head_commit)
1061 return error(_("cannot resolve HEAD commit"));
1062
1063 old_head_tree = repo_get_commit_tree(repo, old_head_commit);
1064 new_head_tree = repo_get_commit_tree(repo, new_head_commit);
1065 if (!old_head_tree || !new_head_tree)
1066 return error(_("cannot resolve tree for HEAD"));
1067
1068 if (oideq(&old_head_tree->object.oid, &new_head_tree->object.oid))
1069 return 0;
1070
1071 *old_head = old_head_commit;
1072 *new_head = new_head_commit;
1073 *changed = true;
1074
1075 return 0;
1076 }
1077
1078 static int cmd_history_drop(int argc,
1079 const char **argv,
1080 const char *prefix,
1081 struct repository *repo)
1082 {
1083 const char * const usage[] = {
1084 GIT_HISTORY_DROP_USAGE,
1085 NULL,
1086 };
1087 enum replay_empty_commit_action empty = REPLAY_EMPTY_COMMIT_DROP;
1088 enum ref_action action = REF_ACTION_DEFAULT;
1089 int dry_run = 0;
1090 struct option options[] = {
1091 OPT_CALLBACK_F(0, "update-refs", &action, "(branches|head)",
1092 N_("control which refs should be updated"),
1093 PARSE_OPT_NONEG, parse_ref_action),
1094 OPT_BOOL('n', "dry-run", &dry_run,
1095 N_("perform a dry-run without updating any refs")),
1096 OPT_CALLBACK_F(0, "empty", &empty, "(drop|keep|abort)",
1097 N_("how to handle descendants that become empty"),
1098 PARSE_OPT_NONEG, parse_opt_empty),
1099 OPT_END(),
1100 };
1101 struct strbuf reflog_msg = STRBUF_INIT;
1102 struct commit *original, *rewritten;
1103 struct rev_info revs = { 0 };
1104 struct replay_result result = { 0 };
1105 struct commit *old_head, *new_head;
1106 bool head_moves = false;
1107 int ret;
1108
1109 argc = parse_options(argc, argv, prefix, options, usage, 0);
1110 if (argc != 1) {
1111 ret = error(_("command expects a single revision"));
1112 goto out;
1113 }
1114 repo_config(repo, git_default_config, NULL);
1115
1116 if (action == REF_ACTION_DEFAULT)
1117 action = REF_ACTION_BRANCHES;
1118
1119 original = lookup_commit_reference_by_name(argv[0]);
1120 if (!original) {
1121 ret = error(_("commit cannot be found: %s"), argv[0]);
1122 goto out;
1123 }
1124
1125 if (!original->parents) {
1126 ret = error(_("cannot drop root commit %s: "
1127 "it has no parent to replay onto"),
1128 argv[0]);
1129 goto out;
1130 } else if (original->parents->next) {
1131 ret = error(_("cannot drop merge commit: %s"), argv[0]);
1132 goto out;
1133 }
1134
1135 ret = setup_revwalk(repo, action, original, &revs);
1136 if (ret)
1137 goto out;
1138
1139 rewritten = original->parents->item;
1140
1141 ret = compute_pending_ref_updates(&revs, action, original, rewritten,
1142 empty, &result);
1143 if (ret) {
1144 ret = error(_("failed replaying descendants"));
1145 goto out;
1146 }
1147
1148 /*
1149 * If HEAD will move as a result of the rewrite then we'll have to
1150 * merge in the changes into the worktree and index. This merge can of
1151 * course conflict, which will cause the whole operation to abort.
1152 *
1153 * If we had already updated the refs at that point then we'd have an
1154 * inconsistent repository state. So we first perform a dry-run merge
1155 * here before updating refs.
1156 */
1157 if (!is_bare_repository(repo)) {
1158 ret = find_head_tree_change(repo, &result, &old_head,
1159 &new_head, &head_moves);
1160 if (ret < 0)
1161 goto out;
1162
1163 if (head_moves && update_worktree(repo, old_head, new_head, true) < 0) {
1164 ret = error(_("dropping this commit would "
1165 "overwrite local changes; aborting"));
1166 goto out;
1167 }
1168 }
1169
1170 strbuf_addf(&reflog_msg, "drop: dropping %s", argv[0]);
1171 ret = apply_pending_ref_updates(repo, &result, reflog_msg.buf, dry_run);
1172 if (ret < 0) {
1173 ret = error(_("failed to update references"));
1174 goto out;
1175 }
1176
1177 if (!dry_run && head_moves && update_worktree(repo, old_head, new_head, false) < 0) {
1178 ret = error(_("could not update working tree to new commit %s"),
1179 oid_to_hex(&new_head->object.oid));
1180 goto out;
1181 }
1182
1183 ret = 0;
1184
1185 out:
1186 replay_result_release(&result);
1187 strbuf_release(&reflog_msg);
1188 release_revisions(&revs);
1189 return ret;
1190 }
1191
1192 int cmd_history(int argc,
1193 const char **argv,
1194 const char *prefix,
1195 struct repository *repo)
1196 {
1197 const char * const usage[] = {
1198 GIT_HISTORY_DROP_USAGE,
1199 GIT_HISTORY_FIXUP_USAGE,
1200 GIT_HISTORY_REWORD_USAGE,
1201 GIT_HISTORY_SPLIT_USAGE,
1202 NULL,
1203 };
1204 parse_opt_subcommand_fn *fn = NULL;
1205 struct option options[] = {
1206 OPT_SUBCOMMAND("drop", &fn, cmd_history_drop),
1207 OPT_SUBCOMMAND("fixup", &fn, cmd_history_fixup),
1208 OPT_SUBCOMMAND("reword", &fn, cmd_history_reword),
1209 OPT_SUBCOMMAND("split", &fn, cmd_history_split),
1210 OPT_END(),
1211 };
1212
1213 argc = parse_options(argc, argv, prefix, options, usage, 0);
1214 return fn(argc, argv, prefix, repo);
1215 }