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