Today I was wrapping up my feature branch which conforms my Awesome Raspberry Pi repo to Kent C. Dodds' all-contributors spec.
I wanted a way to notify myself and contributors of the spec and fail the build with a simple exit 1 if they forgot to add themselves to the CONTRIBUTORS.md file. Using a simple script to get the HEAD commit and see if the file was changed I could easily script this together and fail the build.
But unfortunately this also meant that each time I would add a new feature unrelated to contributors I would fail the build because the file would not change. I know that at work we use Jenkins and can easily check if a branch is a feature branch, starting with feature/
.
Surprisingly, Travis CI has no built-in way to check for git-flow branches or even check consistently for the current branch name! Luckily with a little digging on the internet and especially thanks to this blogpost I found a way to get the branch name, see if it starts with the feature prefix and then perform additional tasks.
before_script:
# Assign the current branch name to env var CURR_BRANCH.
# The Travis CI ENV for the branch name differs if it
# is running a PR build or a branch build.
- export CURR_BRANCH=$(if [ "$TRAVIS_PULL_REQUEST" == "false" ]; then echo $TRAVIS_BRANCH; else echo $TRAVIS_PULL_REQUEST_BRANCH; fi)
script:
# Get the current commit, and list the changed files
# Then pipe output and grep for the file, which exits 0 or 1
- if git diff-tree --no-commit-id --name-only -r $(git rev-parse HEAD) | grep CONTRIBUTORS.md; then
exit 0;
else
echo "Checking if contributors are up to date for branch $CURR_BRANCH"
# See if the branch starts with the prefix using a wildcard glob
if [[ "$CURR_BRANCH" == feature/* ]]; then
echo "Skipping CONTRIBUTORS.md check because build branch is a feature branch";
exit 0;
else
echo "⚠️ Contributor did not add themselve to the CONTRIBUTORS.md list";
exit 1;
fi
fi