Skip to content

Instantly share code, notes, and snippets.

@skarol
Last active July 25, 2022 14:40
Show Gist options
  • Save skarol/a5db1a98c3cca80e8f041baaafd2d132 to your computer and use it in GitHub Desktop.
Save skarol/a5db1a98c3cca80e8f041baaafd2d132 to your computer and use it in GitHub Desktop.
Pre-commit swiftlint hook
#!/bin/bash
if test -d "/opt/homebrew/bin/"; then
PATH="/opt/homebrew/bin/:${PATH}"
fi
export PATH
SWIFT_LINT=swiftlint
if which swiftlint >/dev/null; then
# Export files in SCRIPT_INPUT_FILE_$count to lint against later
count=0
while IFS= read -r file_path; do
export SCRIPT_INPUT_FILE_$count="$file_path"
count=$((count + 1))
done < <(git diff --name-only --cached --diff-filter=d | grep ".swift$")
export SCRIPT_INPUT_FILE_COUNT=$count
if [ "$count" -eq 0 ]; then
echo "No files to lint!"
exit 0
fi
echo "Found $count lintable files! Linting now.."
RESULT=$($SWIFT_LINT --use-script-input-files --strict --config .swiftlint.yml)
NUMBER_OF_ERRORS=$? # swiftline exit value is number of errors
if [ $NUMBER_OF_ERRORS -eq 0 ]; then
printf "\n🎉 Well done. No violation."
else
printf "\n❌ SwiftLint Failed with $NUMBER_OF_ERRORS errors:"
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[31m$TYPE\e[39m\n"
else
printf "\n \e[33m$TYPE\e[39m\n"
fi
printf " \e[90m$FILEPATH:$L:$C\e[39m\n"
printf " $MESSAGE - $DESCRIPTION\n"
done <<< "$RESULT"
printf "\n❌ COMMIT ABORTED. Please fix them before pushing your code.\n"
exit 1
fi
exit $RESULT
else
echo "warning: SwiftLint not installed, install using `brew install swiftlint` or download from https://github.com/realm/SwiftLint"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment