Skip to content

Instantly share code, notes, and snippets.

@zofrex
Created May 11, 2016 22:17
Show Gist options
  • Save zofrex/4a5084c49e4aadd0a3fa0edda14b1fa8 to your computer and use it in GitHub Desktop.
Save zofrex/4a5084c49e4aadd0a3fa0edda14b1fa8 to your computer and use it in GitHub Desktop.
A git pre-commit hook to make sure your Rust code is properly formatted and the tests pass, so you never commit bad code
#!/bin/bash
set -eu
check_char='\xE2\x9C\x93'
cross_char='\xE2\x9D\x8C'
green='\033[0;32m'
nc='\033[0m'
check="$green$check_char$nc"
cross="$green$cross_char$nc"
errors=0
echo -n "Checking formatting... "
diff=$(cargo fmt -- --write-mode diff)
stripped_diff=$(echo "$diff" | sed -e '/^Diff of/d' -e '/^$/d')
if [ -z "$stripped_diff" ]; then
echo -e "$check"
else
echo -e "$cross"
echo "$diff"
errors=1
fi
echo -n "Running tests... "
if result=$(cargo test --color always 2>&1); then
echo -e "$check"
else
echo -e "$cross"
echo "$result"
errors=1
fi
if [ "$errors" != 0 ]; then
echo "Failed"
exit 1
else
echo "OK"
fi
@tbelaire
Copy link

tbelaire commented Sep 9, 2016

This doesn't check against forgetting to git add a file when you create a new module.
I think something like, git stash --keep-index --include-untracked before building will do a better job of testing the actual code to be committed, rather than what's in the working directory. Also important for git add -p
I'll take a crack and getting that to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment