Skip to content

Commit 0efaf0d

Browse files
committed
Fix Checkout behavior when dealing with Head
1 parent cd0a909 commit 0efaf0d

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

LibGit2Sharp.Tests/CheckoutFixture.cs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,40 @@ public void CheckoutLowerCasedHeadThrows()
610610
}
611611
}
612612

613+
[Fact]
614+
public void CanCheckoutAttachedHead()
615+
{
616+
string path = CloneStandardTestRepo();
617+
using (var repo = new Repository(path))
618+
{
619+
Assert.False(repo.Info.IsHeadDetached);
620+
621+
repo.Checkout(repo.Head);
622+
Assert.False(repo.Info.IsHeadDetached);
623+
624+
repo.Checkout("HEAD");
625+
Assert.False(repo.Info.IsHeadDetached);
626+
}
627+
}
628+
629+
[Fact]
630+
public void CanCheckoutDetachedHead()
631+
{
632+
string path = CloneStandardTestRepo();
633+
using (var repo = new Repository(path))
634+
{
635+
repo.Checkout(repo.Head.Tip.Sha);
636+
637+
Assert.True(repo.Info.IsHeadDetached);
638+
639+
repo.Checkout(repo.Head);
640+
Assert.True(repo.Info.IsHeadDetached);
641+
642+
repo.Checkout("HEAD");
643+
Assert.True(repo.Info.IsHeadDetached);
644+
}
645+
}
646+
613647
/// <summary>
614648
/// Helper method to populate a simple repository with
615649
/// a single file and two branches.

LibGit2Sharp/Repository.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -597,6 +597,11 @@ public Branch Checkout(string committishOrBranchSpec, CheckoutOptions checkoutOp
597597

598598
private Branch TryResolveBranch(string committishOrBranchSpec)
599599
{
600+
if (committishOrBranchSpec == "HEAD")
601+
{
602+
return Head;
603+
}
604+
600605
try
601606
{
602607
return Branches[committishOrBranchSpec];
@@ -631,7 +636,7 @@ public Branch Checkout(Branch branch, CheckoutOptions checkoutOptions, CheckoutP
631636
CheckoutTree(branch.Tip.Tree, checkoutOptions, onCheckoutProgress);
632637

633638
// Update HEAD.
634-
if (!branch.IsRemote &&
639+
if (!branch.IsRemote && !(branch is DetachedHead) &&
635640
string.Equals(Refs[branch.CanonicalName].TargetIdentifier, branch.Tip.Id.Sha,
636641
StringComparison.OrdinalIgnoreCase))
637642
{

0 commit comments

Comments
 (0)