From bfa0e39bc1b3f78e04f46c38d5f932d8cbd7c640 Mon Sep 17 00:00:00 2001 From: Isabella Basso Date: Wed, 4 Oct 2023 09:20:22 -0300 Subject: [PATCH] git: preserve HEAD when possible Closes: #2210 --- cli/tests/test_checkout.rs | 17 +++++++++++++++++ lib/src/git.rs | 8 ++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/cli/tests/test_checkout.rs b/cli/tests/test_checkout.rs index c184bb6a4d..efa6c19eef 100644 --- a/cli/tests/test_checkout.rs +++ b/cli/tests/test_checkout.rs @@ -158,6 +158,23 @@ fn test_checkout_conflicting_change_ids() { "###); } +#[test] +fn test_checkout_non_empty_working_copy() { + let test_env = TestEnvironment::default(); + test_env.jj_cmd_ok(test_env.env_root(), &["init", "repo", "--git"]); + let repo_path = test_env.env_root().join("repo"); + + std::fs::write(repo_path.join("one"), "x").unwrap(); + + test_env.jj_cmd_ok(&repo_path, &["describe", "-m", "one"]); + let (_, stderr) = test_env.jj_cmd_ok(&repo_path, &["co", "@-"]); + insta::assert_snapshot!(stderr, @r###" + Working copy now at: kkmpptxz fcdbbd73 (empty) (no description set) + Parent commit : zzzzzzzz 00000000 (empty) (no description set) + Added 0 files, modified 0 files, removed 1 files + "###) +} + fn get_log_output(test_env: &TestEnvironment, cwd: &Path) -> String { let template = r#"commit_id ++ " " ++ description"#; test_env.jj_cmd_success(cwd, &["log", "-T", template]) 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()