Skip to content

Commit 8620b39

Browse files
committed
Improve detection of git root by leveraging SourceLink
The built-in .NET SDKs incorporate source control information already. If we find that, we don't really need to read from the file system the HEAD branch.
1 parent ad9242c commit 8620b39

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

src/ThisAssembly.Git/ThisAssembly.Git.targets

+7-4
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
<!-- Make sure git info is available before calling source generators -->
4646
<Target Name="InitializeGitInformation"
4747
BeforeTargets="GenerateMSBuildEditorConfigFileShouldRun"
48+
AfterTargets="InitializeSourceControlInformation"
4849
DependsOnTargets="InitializeSourceControlInformation;$(SourceLinkUrlInitializerTargets)">
4950

5051
<PropertyGroup Condition="'$(SourceControlInformationFeatureSupported)' == 'true'">
@@ -71,10 +72,12 @@
7172
<Warning Code="TA001" Text="A valid SourceLink provider does not seem to be installed for the current repository/project. Some values may be empty." Condition="'$(SourceLinkUrl)' == ''" />
7273

7374
<PropertyGroup Condition="'$(RepositoryBranch)' == '' and '$(RepositoryRoot)' != ''">
74-
<!-- We may not be in CI at all. If we got a git repo root, we can directly read HEAD -->
75-
<RepositoryHead>$(RepositoryRoot).git/HEAD</RepositoryHead>
76-
<RepositoryBranch Condition="Exists($(RepositoryHead))">$([System.IO.File]::ReadAllText($(RepositoryHead)).Trim())</RepositoryBranch>
77-
<RepositoryBranch Condition="$(RepositoryBranch) != ''">$(RepositoryBranch.TrimStart("ref:").Trim().TrimStart("refs").Trim("/").TrimStart("heads").Trim("/").Trim())</RepositoryBranch>
75+
<!-- If we didnd't populate from CI/ENV, we can still use the source control provider itself to get the branch name -->
76+
<_ThisAssemblyGitBranchName>@(_ThisAssemblyGitSourceRoot -> '%(BranchName)')</_ThisAssemblyGitBranchName>
77+
<!-- The above only works on .NET SDK 9.0+, so account for 8.0 implicit nuget package -->
78+
79+
<_ThisAssemblyGitBranchName Condition="'$(_ThisAssemblyGitBranchName)' == ''">$([System.IO.File]::ReadAllText('$(RepositoryRoot).git/HEAD').Trim())</_ThisAssemblyGitBranchName>
80+
<RepositoryBranch>$(_ThisAssemblyGitBranchName.TrimStart("ref:").Trim().Replace('refs/heads/', '').Replace('refs/tags/', ''))</RepositoryBranch>
7881
</PropertyGroup>
7982

8083
</Target>

0 commit comments

Comments
 (0)