Created
February 14, 2016 20:14
-
-
Save aschweer/6e63f69b263c5c78ac57 to your computer and use it in GitHub Desktop.
git pre-commit hook to check XML files for well-formedness, using 'file' and 'xmllint' commands
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# An example hook script to verify what is about to be committed. | |
# Called by "git commit" with no arguments. The hook should | |
# exit with non-zero status after issuing an appropriate message if | |
# it wants to stop the commit. | |
# | |
# To enable this hook, rename this file to "pre-commit". | |
if git rev-parse --verify HEAD >/dev/null 2>&1 | |
then | |
against=HEAD | |
else | |
# Initial commit: diff against an empty tree object | |
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 | |
fi | |
check_xml_wellformed() | |
{ | |
for FILE in `git diff-index --name-only --cached $against -- ` ; do | |
mimetype=`file --brief --mime-type $FILE` | |
# if file is an xml file, check that it is well-formed | |
if [ $mimetype == 'application/xml' ]; then | |
if ! xmllint --noout $FILE; then | |
echo "=========================================================" | |
echo "Unstaging $FILE for the commit -- XML but not well-formed" | |
git reset -q HEAD $FILE | |
retval=1 | |
else | |
echo "XML check for $FILE: OK" | |
fi | |
fi | |
done | |
if [[ $retval -gt 0 ]]; then | |
exit $retval | |
fi | |
} | |
check_xml_wellformed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have found that you can sneak a file past this if you have the
.xml
extension but have it not be a valid XML file. The mime-type check fails soxmllint
never runs.Version that uses a file extension check rather than mime-type
https://gist.github.com/robilic/e86313fcb3ff7f763b43c43a43f508a0