Skip to content

Instantly share code, notes, and snippets.

@milankamilya
Last active September 8, 2023 08:19
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save milankamilya/fa99490dcc2e9234a8fdb0110aa2a729 to your computer and use it in GitHub Desktop.
Save milankamilya/fa99490dcc2e9234a8fdb0110aa2a729 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 -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
@EvgenyKarkan
Copy link

Hey, looks like you have a typo here, should be -quiet instead of quite.

@milankamilya
Copy link
Author

Hey @EvgenyKarkan, Thanks for informing. correction done.

@YogeshBhattGWL
Copy link

YogeshBhattGWL commented Aug 10, 2022

@milankamilya But I want to also push this file to Git... How can I do that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment