Skip to content

Instantly share code, notes, and snippets.

@alielsokary
Last active August 20, 2020 06:59
Show Gist options
  • Save alielsokary/648194fd7a3862207ba9b7433bd12deb to your computer and use it in GitHub Desktop.
Save alielsokary/648194fd7a3862207ba9b7433bd12deb to your computer and use it in GitHub Desktop.
Swiftlint pre-commit hook
# add this to .git/hooks directory without any file extension like so 'pre-commit'.
# run chmod +x pre-commit to give it the proper permission.
# this script runs swiftlint from Pods. But it's recommended to also
# install swiftlint with brew to quickly run 'swiftlint autocorrect' in the project root directory.
#!/bin/bash
# Finding SwiftLint
LINT=./Pods/SwiftLint/swiftlint
if [[ -e "${LINT}" ]]; then
echo "SwiftLint version: $(${LINT} version)"
echo "SwiftLint Start..."
else
echo "SwiftLint does not exist, please download from https://github.com/realm/SwiftLint"
exit 1
fi
count=0
# Function to add files to Lint
function addFilesToLint {
filename=""
count=$2
for item in $1
do
if [[ $item == *".swift"* ]]; then
filename+="$item"
export SCRIPT_INPUT_FILE_$count="$filename"
count=$((count + 1))
filename=""
else
filename+="$item "
fi
done
}
# Getting files which are in commit and haven't been pushed yet
targets=$(git diff --stat --cached --name-only $(git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD)) | grep -F ".swift")
addFilesToLint "${targets[0]}" $count
export -p | grep SCRIPT_INPUT_FILE
export SCRIPT_INPUT_FILE_COUNT=$count
RESULT=$($LINT lint --quiet --use-script-input-files)
if [ "$RESULT" == '' ]; then
printf "\eSwiftLint Finished.\e\n"
else
echo ""
printf "\eSwiftLint Failed.\e Please check below:\n"
while read -r line; do
FILEPATH=$(echo $line | cut -d : -f 1)
L=$(echo $line | cut -d : -f 2)
C=$(echo $line | cut -d : -f 3)
TYPE=$(echo $line | cut -d : -f 4 | cut -c 2-)
MESSAGE=$(echo $line | cut -d : -f 5 | cut -c 2-)
DESCRIPTION=$(echo $line | cut -d : -f 6 | cut -c 2-)
if [ "$TYPE" == 'error' ]; then
printf "\n \e$TYPE\e\n"
else
printf "\n \e$TYPE\e\n"
fi
printf " \e$FILEPATH:$L:$C\e\n"
printf " $MESSAGE - $DESCRIPTION\n"
done <<< "$RESULT\n"
printf "Commit ABORTED. Please run 'swiftlint autocorrect' or fix violations manually before commit.\n"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment