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 29, 2023
1 parent 19a658e commit 89ee21e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
17 changes: 17 additions & 0 deletions cli/tests/test_checkout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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])
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(RefTarget::normal(first_parent_id.clone()));
}
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 89ee21e

Please sign in to comment.