Skip to content

Commit 403fc23

Browse files
committed
Ensure Tags can be created in detached Head state
Fix #791
1 parent 805e9b0 commit 403fc23

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

LibGit2Sharp.Tests/TagFixture.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,7 @@ public void CreatingATagForHeadInAEmptyRepositoryThrows()
247247
using (var repo = new Repository(repoPath))
248248
{
249249
Assert.Throws<LibGit2SharpException>(() => repo.ApplyTag("mytaghead", "HEAD"));
250+
Assert.Throws<LibGit2SharpException>(() => repo.ApplyTag("mytaghead"));
250251
}
251252
}
252253

@@ -287,6 +288,26 @@ public void CanAddATagForImplicitHead()
287288
}
288289
}
289290

291+
[Fact]
292+
public void CanAddATagForImplicitHeadInDetachedState()
293+
{
294+
string path = CloneStandardTestRepo();
295+
using (var repo = new Repository(path))
296+
{
297+
repo.Checkout(repo.Head.Tip);
298+
299+
Assert.True(repo.Info.IsHeadDetached);
300+
301+
Tag tag = repo.ApplyTag("mytag");
302+
Assert.NotNull(tag);
303+
304+
Assert.Equal(repo.Head.Tip.Id, tag.Target.Id);
305+
306+
Tag retrievedTag = repo.Tags[tag.CanonicalName];
307+
Assert.Equal(retrievedTag, tag);
308+
}
309+
}
310+
290311
[Fact]
291312
// Ported from cgit (https://github.com/git/git/blob/1c08bf50cfcf924094eca56c2486a90e2bf1e6e2/t/t7004-tag.sh#L87)
292313
public void CreatingADuplicateTagThrows()

LibGit2Sharp/RepositoryExtensions.cs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ private static void EnsureNoGitLink<T>() where T : GitObject
6868
/// <param name="tagName">The name of the tag to create.</param>
6969
public static Tag ApplyTag(this IRepository repository, string tagName)
7070
{
71-
return ApplyTag(repository, tagName, repository.Head.CanonicalName);
71+
return ApplyTag(repository, tagName, RetrieveHeadCommitId(repository, "Cannot apply Tag.").Sha);
7272
}
7373

7474
/// <summary>
@@ -91,7 +91,16 @@ public static Tag ApplyTag(this IRepository repository, string tagName, string o
9191
/// <param name="message">The annotation message.</param>
9292
public static Tag ApplyTag(this IRepository repository, string tagName, Signature tagger, string message)
9393
{
94-
return ApplyTag(repository, tagName, repository.Head.CanonicalName, tagger, message);
94+
return ApplyTag(repository, tagName, RetrieveHeadCommitId(repository, "Cannot apply Tag.").Sha, tagger, message);
95+
}
96+
97+
private static ObjectId RetrieveHeadCommitId(IRepository repository, string message)
98+
{
99+
Commit commit = repository.Head.Tip;
100+
101+
Ensure.GitObjectIsNotNull(commit, "HEAD");
102+
103+
return commit.Id;
95104
}
96105

97106
/// <summary>

0 commit comments

Comments
 (0)