starbeamrainbowlabs
starbeamrainbowlabs

Reputation: 6106

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?

Upvotes: 1

Views: 546

Answers (1)

stijn
stijn

Reputation: 35901

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:

  • The 2> NUL redirects standard error to the output so GitTag will be empty in case of an error, in which case it's set to 'unknown'
  • Relying on the current directory is nearly always a bad idea so specify the directory to run git in explicitly in a property
  • Same for the output file

Upvotes: 2

Related Questions