Skip to content

Instantly share code, notes, and snippets.

@burubur
Created June 14, 2020 00:13
Show Gist options
  • Save burubur/ebf2cfdf77ae8c15b6ba4b12537cc6aa to your computer and use it in GitHub Desktop.
Save burubur/ebf2cfdf77ae8c15b6ba4b12537cc6aa to your computer and use it in GitHub Desktop.
Generate mock file based on interface changes using mockgen
#!/usr/bin/env bash
# mockgen will generates a mock file based on interface changes
# example:
# there is changes on the following interface
# /pkg/sharedcontract/httpconnector.go
# then the mock will be generated to:
# /test/fixture/mock/httpconnector_mock.go
#
# for further mock usage, refer to https://github.com/golang/mock
if ! mockgen --version >/dev/null 2>&1; then echo "please run make dev.setup first to install the dependency"; fi;
# Get changed files
files=$(git diff --name-only | sort | uniq)
for file in $files;
do
if [[ ${file} != "mocks"* && ${file} != *"_test"* && ${file} == *".go" ]]; then
filename=$(basename -- ${file%%.*})
dir=$(dirname $file)
package="$(basename "$(dirname "$file")")"
echo ${package}
dest="test/fixture/mock/${filename}_mock.go"
echo ${dest}
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
$(go env GOPATH)/bin/mockgen -source=${file} -destination=${dest} -package="mock"
git add ${dest}
echo "${dest} is generated"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment