How to lookup the latest git commit hash from an ant build script
I wrote the following ant target for a project on github. Usage:
- stores version in property "repository.version"
- works if no git is installed or no .git directory is present (fallback)
- other targets must depend on this target if they need the git version
- only one git command gets executed (--always)
<available file=".git" type="dir" property="git.present"/><target name="git.revision" description="Store git revision in ${repository.version}" if="git.present"> <exec executable="git" outputproperty="git.revision" failifexecutionfails="false" errorproperty=""> <arg value="describe"/> <arg value="--tags"/> <arg value="--always"/> <arg value="HEAD"/> </exec> <condition property="repository.version" value="${git.revision}" else="unknown"> <and> <isset property="git.revision"/> <length string="${git.revision}" trim="yes" length="0" when="greater"/> </and> </condition></target>
It e.g. be used for expanding the token @repository.version@
in a template file:
<target name="index.html" depends="git.revision" description="build index.html from template"> <copy file="index.html.template" tofile="index.html" overwrite="yes"> <filterchain> <replacetokens> <token key="repository.version" value="${repository.version}" /> </replacetokens> </filterchain> </copy></target>
This command returns always the working folder's last commit SHA1, useful when you don't always build from HEAD. The command should run both on Windows and *nix systems
<exec executable="git" outputproperty="git.revision"> <arg value="log" /> <arg value="-1" /> <arg value="--pretty=format:%H" /></exec>