Skip to content

Commit

Permalink
git: preserve HEAD when possible
Browse files Browse the repository at this point in the history
Closes: jj-vcs#2210
  • Loading branch information
isinyaaa committed Oct 30, 2023
1 parent 19a658e commit 07ccfca
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
26 changes: 26 additions & 0 deletions cli/tests/test_git_colocated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,32 @@ fn test_git_colocated_conflicting_git_refs() {
"###);
}

#[test]
fn test_git_colocated_checkout_non_empty_working_copy() {
let test_env = TestEnvironment::default();
let workspace_root = test_env.env_root().join("repo");
git2::Repository::init(&workspace_root).unwrap();
test_env.jj_cmd_ok(&workspace_root, &["init", "--git-repo", "."]);
test_env.jj_cmd_ok(&workspace_root, &["new", "-m", "foo"]);

std::fs::write(workspace_root.join("one"), "x").unwrap();

test_env.jj_cmd_ok(&workspace_root, &["co", "@-"]);
let (_, stderr) = test_env.jj_cmd_ok(&workspace_root, &["describe", "-m", "bar"]);
insta::assert_snapshot!(stderr, @r###"
Working copy now at: kkmpptxz c3a22cf1 (empty) bar
Parent commit : qpvuntsm 230dd059 (empty) (no description set)
"###);

insta::assert_snapshot!(get_log_output(&test_env, &workspace_root), @r###"
@ c3a22cf1b56281238683d897419c0f09f10331e2 bar
│ ◉ 96d5d16db6ff3cf2bcb066137c2490090eb9f88b foo
├─╯
◉ 230dd059e1b059aefc0da06a2e5a7dbf22362f22 HEAD@git
◉ 0000000000000000000000000000000000000000
"###);
}

#[test]
fn test_git_colocated_fetch_deleted_or_moved_branch() {
let test_env = TestEnvironment::default();
Expand Down
8 changes: 6 additions & 2 deletions lib/src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -809,11 +809,15 @@ pub fn reset_head(
) -> Result<(), git2::Error> {
let first_parent_id = &wc_commit.parent_ids()[0];
if first_parent_id != mut_repo.store().root_commit_id() {
let first_parent = RefTarget::normal(first_parent_id.clone());
let git_head = mut_repo.view().git_head();
let new_git_commit_id = Oid::from_bytes(first_parent_id.as_bytes()).unwrap();
let new_git_commit = git_repo.find_commit(new_git_commit_id)?;
git_repo.set_head_detached(new_git_commit_id)?;
if git_head != &first_parent {
git_repo.set_head_detached(new_git_commit_id)?;
mut_repo.set_git_head_target(first_parent);
}
git_repo.reset(new_git_commit.as_object(), git2::ResetType::Mixed, None)?;
mut_repo.set_git_head_target(RefTarget::normal(first_parent_id.clone()));
} else {
// Can't detach HEAD without a commit. Use placeholder ref to nullify the HEAD.
// We can't set_head() an arbitrary unborn ref, so use reference_symbolic()
Expand Down

0 comments on commit 07ccfca

Please sign in to comment.