diff --git a/cli/tests/test_git_colocated.rs b/cli/tests/test_git_colocated.rs index 1937b4c2a2..c65c2122cc 100644 --- a/cli/tests/test_git_colocated.rs +++ b/cli/tests/test_git_colocated.rs @@ -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(); diff --git a/lib/src/git.rs b/lib/src/git.rs index d2540d5c34..6e4a85c5ab 100644 --- a/lib/src/git.rs +++ b/lib/src/git.rs @@ -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()