dgiot/scripts/elvis-check.sh

85 lines
1.9 KiB
Bash
Raw Normal View History

2021-05-18 14:54:48 +08:00
#!/usr/bin/env bash
## This script checks style of changed files.
## Expect argument 1 to be the git compare base.
set -euo pipefail
2022-01-07 16:30:56 +08:00
elvis_version='1.0.0-emqx-2'
2021-05-18 14:54:48 +08:00
base="${1:-}"
2022-01-07 16:30:56 +08:00
repo="${2:-emqx/emqx}"
REPO="${GITHUB_REPOSITORY:-${repo}}"
2021-05-18 14:54:48 +08:00
if [ "${base}" = "" ]; then
echo "Usage $0 <git-compare-base-ref>"
exit 1
fi
echo "elvis -v: $elvis_version"
echo "git diff base: $base"
if [ ! -f ./elvis ] || [ "$(./elvis -v | grep -oE '[1-9]+\.[0-9]+\.[0-9]+\-emqx-[0-9]+')" != "$elvis_version" ]; then
2021-05-22 02:06:00 +08:00
curl --silent --show-error -fLO "https://github.com/emqx/elvis/releases/download/$elvis_version/elvis"
2021-05-18 14:54:48 +08:00
chmod +x ./elvis
fi
if [[ "$base" =~ [0-9a-f]{8,40} ]]; then
# base is a commit sha1
compare_base="$base"
else
2022-01-07 16:30:56 +08:00
remote="$(git remote -v | grep -E "github\.com(:|/)$REPO((\.git)|(\s))" | grep fetch | awk '{print $1}')"
2021-05-18 14:54:48 +08:00
git fetch "$remote" "$base"
compare_base="$remote/$base"
fi
git_diff() {
git diff --name-only --diff-filter=ACMRTUXB "$compare_base"...HEAD
}
bad_file_count=0
for file in $(git_diff); do
if [ ! -f "$file" ]; then
# file is deleted, skip
continue
fi
if [[ $file != *.erl ]]; then
# not .erl file
continue
fi
if ! ./elvis rock "$file" -c elvis.config; then
bad_file_count=$(( bad_file_count + 1))
fi
done
if [ $bad_file_count -gt 0 ]; then
echo "elvis: $bad_file_count errors"
exit 1
fi
2022-01-07 16:30:56 +08:00
### now check new-line at EOF for changed files
nl_at_eof() {
local file="$1"
if ! [ -f "$file" ]; then
return
fi
case "$file" in
*.png|*rebar3)
return
;;
esac
local lastbyte
lastbyte="$(tail -c 1 "$file" 2>&1)"
if [ "$lastbyte" != '' ]; then
echo "$file"
return 1
fi
}
for file in $(git_diff); do
if ! nl_at_eof "$file"; then
bad_file_count=$(( bad_file_count + 1 ))
fi
done
exit $bad_file_count