Skip to content

Instantly share code, notes, and snippets.

@JasonCanCode
Created January 21, 2021 17:28
Show Gist options
  • Save JasonCanCode/e0ece0b8aad8dc01ea1f11800e976dde to your computer and use it in GitHub Desktop.
Save JasonCanCode/e0ece0b8aad8dc01ea1f11800e976dde to your computer and use it in GitHub Desktop.
Git commit hooks for running SwiftLint
#!/usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
echo "Running from" $DIR
ln -s $DIR/pre-commit $DIR/../.git/hooks/pre-commit
#!/bin/bash
echo "Running autocorrect"
swiftlint autocorrect 2>/dev/null | tee /dev/stderr | sed 's/:.*//g' | xargs git add
echo "Running lint"
swiftlint 2>/dev/null | tee /tmp/lintout | grep error:
if [ $? -eq 0 ]; then
echo "Lint failed. Please address errors above."
exit 1
fi
for file in `git diff --cached --name-only`; do
grep "\"$file\"" /tmp/lintout > /tmp/grepout
if [ $? -eq 0 ]; then
echo "************************************"
echo "* There are warnings in a file you have updated."
echo "* Please consider fixing them before pushing."
echo "* File: $file"
echo "************************************"
cat /tmp/grepout
fi
done
exit 0
@JasonCanCode
Copy link
Author

Use SwiftLint to enforce much of your code styling preferences. Install it on your machine using Homebrew.

brew install swiftlint

To take advantage of the autocorrect feature and prevent committing any code with linter errors, use this pre-commit hook. To setup, go to the root project directory and add the two files to a tools folder. Then from that folder in Terminal, run:

./add_git_hooks.sh

Now whenever you go to commit, autocorrect will be applied and any linter errors will prevent the commit from completing.

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