buildmsbuildxbuild

Optional PreBuildEvent in MSBuild?


Is it possible to have an optional <PreBuildEvent> in a *.csproj file? I have the following:

<PropertyGroup>
  <PreBuildEvent>git rev-parse HEAD &gt;../../git-hash.txt</PreBuildEvent>
</PropertyGroup>

This outputs the latest git hash to a file, which is embedded in the executable elsewhere.

Since I'm a University student, I'm often writing code on the University machines (and not my linux machine at home) which have SVN and not git, causing the build process to fail. Is it possible to make the above <PreBuildEvent /> optional so that if git isn't installed the build process doesn't fail?


Solution

  • Just skipping the build event would leave you with an empty git-hash.txt so that doesn't seem the best idea. Instead you could just try to run the git command, and if it fails write a dummy hash to the file. I don't know the command line syntax to do that (a PreBuildEvent runs under cmd.exe) so here's an msbuild solution. Because of the BeforeTargets="Build" it will run before the build as well.

    <Target Name="WriteGitHash" BeforeTargets="Build">
      <Exec Command="git --work-tree=$(Repo) --git-dir=$(Repo)\.git rev-parse HEAD 2> NUL" ConsoleToMSBuild="true" IgnoreExitCode="True">
        <Output TaskParameter="ConsoleOutput" PropertyName="GitTag" />
      </Exec>
      <PropertyGroup>
        <GitTag Condition="'$(GitTag)' == ''">unknown</GitTag>
      </PropertyGroup>
      <WriteLinesToFile File="$(Repo)\git-hash.txt" Lines="$(GitTag)" Overwrite="True"/>
    </Target>
    

    Some notes: