Skip to content

Instantly share code, notes, and snippets.

@ihusnainalii
Last active September 30, 2024 07:57
Show Gist options
  • Save ihusnainalii/e597cab7ec81f65c3ed10180978e1b06 to your computer and use it in GitHub Desktop.
Save ihusnainalii/e597cab7ec81f65c3ed10180978e1b06 to your computer and use it in GitHub Desktop.
pre-commit git hook for iOS projects
#----------------------------------------------------------------
# PREVENT YOUR CODEBASE GETTING SPOILED BY DEVELOPERS
# - YOU NEED TO THIS pre-commit file (without any extension)
# at ".git/hooks/" folder.
# - THEN TRY TO PUT WRONG STYLED/LINT CODE
#----------------------------------------------------------------
branch="$(git rev-parse --abbrev-ref HEAD)"
#----------------------------------------------------------------
# RESTRICT BRANCHES FROM DIRECT PUSH
#----------------------------------------------------------------
if [ "$branch" = "master" ] || [ "$branch" = "Development" ]; then
echo "You can't commit directly to $branch"
exit 1
fi
#----------------------------------------------------------------
# RUN SWIFTLINT
#----------------------------------------------------------------
# Run SwiftLint
START_DATE=$(date +"%s")
# This line is required to make sure it works on Apple Silicon.
if [[ "$(uname -m)" == arm64 ]]; then
export PATH="/opt/homebrew/bin:$PATH"
fi
# Variables
SWIFT_LINT=/usr/local/bin/swiftlint
hasErrors=0
# Run SwiftLint for given filename
run_swiftlint() {
local filename="${1}"
if [[ "${filename##*.}" == "swift" ]]; then
${SWIFT_LINT} lint --path "${filename}"
if [[ $? != 0 ]]; then
hasErrors=1
fi
fi
}
if [[ -e "${SWIFT_LINT}" ]]; then
echo "SwiftLint version: $(${SWIFT_LINT} version)"
# Run for staged files
for filename in $(git diff --diff-filter=d --name-only);
do
run_swiftlint "${filename}";
done
# Run for unstaged files
for filename in $(git diff --cached --diff-filter=d --name-only);
do
run_swiftlint "${filename}";
done
# Run for added files
for filename in $(git ls-files --others --exclude-standard);
do
run_swiftlint "${filename}";
done
else
echo "${SWIFT_LINT} is not installed."
exit 0
fi
END_DATE=$(date +"%s")
DIFF=$(($END_DATE - $START_DATE))
echo "SwiftLint took $(($DIFF / 60)) minutes and $(($DIFF % 60)) seconds to complete."
# Show error message if hasErrors is true and exit with an error status
if [[ $hasErrors -ne 0 ]]; then
echo "SwiftLint checks failed. Please fix the above issues."
exit 1
fi
exit 0
#----------------------------------------------------------------
# BUILD XCODE PROJECT & VALIDATE
#----------------------------------------------------------------
xcodebuild -quiet build -workspace <YOUR WORKSPACE>.xcworkspace -scheme <YOUR PROJECT SCHEME>
if test $? -eq 0
then echo "Successful build"
else
echo "Your XCode build is Failed, for scheme "
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment