Last active
September 13, 2023 11:53
-
-
Save emndeniz/80407a44517f7c7f07a50a517cfa3a51 to your computer and use it in GitHub Desktop.
PreCommitHook for SwiftLint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# COLOR codes to use in logs | |
RED='\033[0;31m' | |
YELLOW='\033[1;33m' | |
GREEN='\033[0;32m' | |
BOLD='\033[1m' | |
NC='\033[0m' # No Color | |
# LOG tag of file | |
LOG_TAG="PRE_COMMIT_HOOK_LOG :: " | |
# swiftlint.yml path. | |
LINT_CONFIG_FILE=".swiftlint.yml" | |
set -e | |
# check if lint exists. | |
if ! command -v swiftlint &> /dev/null | |
then | |
echo -e "${LOG_TAG}${RED}SwiftLint could not be found. Please install it in your computer.${NC}" | |
exit 1 | |
fi | |
echo -e "${LOG_TAG}Linting..." | |
#Always lint one file to prevent "No lintable files found at paths: ''" | |
export SCRIPT_INPUT_FILE_0="##Put one of your files with its path that will always be in your project. (For Ex: AppDelegate)" | |
# This variable will store the files that needs to be re-added after auto fix. | |
FILES_TO_ADD="" | |
swiftFileCount=1 | |
# We will count the changed files and apply lint only for them. | |
while IFS= read -r file_path; do | |
export SCRIPT_INPUT_FILE_$swiftFileCount="$file_path" | |
swiftFileCount=$((swiftFileCount + 1)) | |
# We should escape from whitespace paths. | |
escaped_path="${file_path// /\\ }" | |
FILES_TO_ADD+="'$escaped_path' " | |
done < <(git diff --diff-filter=d --name-only --cached | grep ".swift$") | |
echo -e "${LOG_TAG}The count of Swift files you changed and add to git is '${BOLD}$swiftFileCount${NC}'" | |
# In case there is no change besides the default 'Classes/Constants.swift' don't run the lint | |
if [ "$swiftFileCount" -ne 1 ]; then | |
export SCRIPT_INPUT_FILE_COUNT=$swiftFileCount | |
if swiftlint --fix --strict --use-script-input-files --config $LINT_CONFIG_FILE && swiftlint --use-script-input-files --config $LINT_CONFIG_FILE --force-exclude --strict; then | |
# Re-add files after lint fix. Otherwise we can't send the auto fixed codes to the remote. | |
# adding with echo prevents incorrect file addings. | |
echo "git add ${FILES_TO_ADD}" | |
echo -e "${GREEN}${LOG_TAG}No Swift Lint violations found. Your commit is good to go.${NC}" | |
exit 0 | |
else | |
echo -e "${RED}${LOG_TAG}'${BOLD}swiftlint fix${NC}' ${RED}could not fix the problem. Please check the link failures in your code!!!${NC}" | |
exit 1 | |
fi | |
else | |
echo -e "${LOG_TAG}${YELLOW}No files to lint!${NC}" | |
exit 0 | |
fi | |
# Unset the environment variables | |
unset "SCRIPT_INPUT_FILE_COUNT" | |
for ((i=0; i<swiftFileCount; i++)); do | |
unset "SCRIPT_INPUT_FILE_$i" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment