Skip to content

Instantly share code, notes, and snippets.

Last active April 22, 2023 09:32
  • Star 59 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Git Pre-Commit hook with SwiftLInt
#Path to swiftlint
#if $SWIFT_LINT >/dev/null 2>&1; then
if [[ -e "${SWIFT_LINT}" ]]; then
for file_path in $(git ls-files -m --exclude-from=.gitignore | grep ".swift$"); do
export SCRIPT_INPUT_FILE_$count=$file_path
count=$((count + 1))
##### Check for modified files in unstaged/Staged area #####
for file_path in $(git diff --name-only --cached | grep ".swift$"); do
export SCRIPT_INPUT_FILE_$count=$file_path
count=$((count + 1))
##### Make the count avilable as global variable #####
##### Lint files or exit if no files found for lintint #####
if [ "$count" -ne 0 ]; then
echo "Found lintable files! Linting and fixing the fixible parts..."
$SWIFT_LINT autocorrect --use-script-input-files --config .swiftlint.yml #autocorrects before commit.
echo "No files to lint!"
exit 0
if [ $RESULT -eq 0 ]; then
echo ""
echo "Violation found of the type WARNING! Must fix before commit!"
echo ""
echo "Violation found of the type ERROR! Must fix before commit!"
exit $RESULT
#### If SwiftLint is not installed, do not allow commit
echo "warning: SwiftLint not installed, download from"
echo "If you have Homebrew, you can directly use `brew install swiftlint` to install SwiftLint"
exit 1
Copy link

fabb commented Jul 8, 2018

Good idea to check only changed files!
Question: why check unstaged files that won‘t be committed as well (git ls-files -m)?

Copy link

fabb commented Jul 9, 2018

The script is not ideal for several reasons:

  1. It checks both staged and unstaged files, this might not always be wanted
  2. If a file has both staged and unstaged changes (e.g. only add some hunks of all the changes in a file), then this script will add the file twice
  3. It includes deleted files which will make swiftlint crash - --diff-filter=d can be used on git diff to exclude deleted staged files - for git ls-files i'm not sure how to hide removed files
  4. The script autocorrects also unstaged files, even if the commit succeeds
  5. It would not work correctly if for example I make stage some changes to a file, and then move the file (unstaged)

Copy link

Is there a way to fix the issue with deleted files?

Copy link

m0hitnnd commented Feb 20, 2019

@kpavankotesh You can use something like this - git diff --diff-filter=d --staged. --diff-filter=d filters outs deleted files and --staged accepts only staged files.

Copy link

JAIRMG commented Nov 10, 2020

Great post on Medium! I have a question, is there a way to remove the header comments generated by XCode?

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