Skip to content

Instantly share code, notes, and snippets.

@rizalgowandy
Created June 17, 2019 02:48
Show Gist options
  • Save rizalgowandy/af6b652916b37d30bbd98292e18652dd to your computer and use it in GitHub Desktop.
Save rizalgowandy/af6b652916b37d30bbd98292e18652dd to your computer and use it in GitHub Desktop.
Automatic Go Mock Generator
#!/usr/bin/env bash
# mockgen will generates mock interface
# for your changes from master branch into mock directory
# Example :
# /src/order.go
#
# your mock will generated to
#
# /mocks/mock_src/order_mock.go
#
# Mock usage refer to https://github.com/golang/mock
curBranch=$(git branch | grep \* | cut -d ' ' -f2)
if [[ ${curBranch} = "master" ]] || [[ ${curBranch} = "staging" ]] ; then
echo "Generate mock in master or staging branch is forbidden"
exit 0
fi
go get -u github.com/golang/mock/...
go install github.com/golang/mock/mockgen
# get parent commit of this branch from master
parentCommit=$(git log --author="SyncToped" --max-count=1 --pretty=format:"%h" )
files=$(git diff $curBranch..$parentCommit --name-only & git diff --name-only | sort | uniq)
for file in $files;
do
if [[ ${file} != "mocks"* && ${file} != *"_test"* && ${file} == *".go" ]]; then
dest="mocks/$(echo ${file} | sed 's/^/mock_/; s/\//\/mock_/g')"
if [[ ! -f ${file} && -f ${dest} ]]; then
rm ${dest}
git add ${dest}
continue
fi
if [[ -f ${file} && $(cat ${file} | grep -i ".* interface {" | wc -l) -ne 0 ]]; then
${GOPATH}/bin/mockgen -source=${file} -destination=${dest}
git add ${dest}
echo -e "\e[0m${dest} is \e[32mgenerated"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment