Skip to content

Instantly share code, notes, and snippets.

@micheltlutz
Forked from milankamilya/pre-commit
Created March 24, 2020 11:48
Show Gist options
  • Save micheltlutz/c669475658d91a7e85534652ad41de15 to your computer and use it in GitHub Desktop.
Save micheltlutz/c669475658d91a7e85534652ad41de15 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")
SWIFT_LINT=/usr/local/bin/swiftlint
# Run SwiftLint for given filename
run_swiftlint() {
local filename="${1}"
if [[ "${filename##*.}" == "swift" ]]; then
${SWIFT_LINT} autocorrect --path "${filename}"
${SWIFT_LINT} lint --path "${filename}"
fi
}
if [[ -e "${SWIFT_LINT}" ]]; then
echo "SwiftLint version: $(${SWIFT_LINT} version)"
# Run for both staged and unstaged files
git diff --name-only | while read filename; do run_swiftlint "${filename}"; done
git diff --cached --name-only | while read filename; do run_swiftlint "${filename}"; done
else
echo "${SWIFT_LINT} is not installed. Please install it first from https://www.github.com/realm/SwiftLint"
exit 0
fi
END_DATE=$(date +"%s")
DIFF=$(($END_DATE - $START_DATE))
echo "SwiftLint took $(($DIFF / 60)) minutes and $(($DIFF % 60)) seconds to complete."
#----------------------------------------------------------------
# BUILD XCODE PROJECT & VALIDATE
#----------------------------------------------------------------
xcodebuild quite 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