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