When running from Visual Studio, MSBuild is given the $(SolutionDir)
macro/property.
Running from Azure DevOps, this property does not exist (rightfully so).
Azure DevOps has the Build.SourceBranch
variable which can be passed to MsBuild as a property. This variable is better because it points directly to the repository root while $(SolutionDir)
may point to a sub-directory if the solution is not in the root.
Is there a consistent MsBuild property I can use in both Visual Studio and Azure DevOps which can point to the repository root?
One way to achieve this is to have a Directory.Build.props
file in the repository root and Specify a property <RepositoryRoot>$(MSBuildThisFileDirectory)</RepositoryRoot>
however one restriction I have prevents me from doing this.
I would strongly recommend not using .gitignore to find the root of a Git repo. It's possible to have that file in any directory.
I assume Azure DevOps uses Git as the underlying SCM and not TFS these days.
Here's a more direct way to get your Git repo root.
<Target Name="GetGitRoot" BeforeTargets="BeforeBuild">
<Exec Command="git rev-parse --show-toplevel" ConsoleToMSBuild="true">
<Output TaskParameter="ConsoleOutput" PropertyName="GitRootDirectory"/>
</Exec>
</Target>
<PropertyGroup>
<RootDirectory>$(GitRootDirectory)</RootDirectory>
</PropertyGroup>
The property below is just showing how to use it. You can use $(GitRootDirectory)
directly. Just make sure your BeforeTargets happens before you use it.