Skip to content

Pre commit hook for linters

Ivey Padgett edited this page Jun 2, 2016 · 2 revisions

This is a pre commit hook to automatically run linters (tslint and stylelint) before a commit can be made. I created this to force myself to run the linters before commiting.

Instructions

You have never added any pre commit hooks to this project

You should have a file called pre-commit.sample inside of your .git/hooks folder in your project base, replace the internals of pre-commit.sample with the code for the hook and rename pre-commit.sample to pre-commit in the same folder.

Steps:

  1. Add the code for the hook to [project]/.git/hooks/pre-commit.sample
  2. Rename [project]/.git/hooks/pre-commit.sample to [project]/.git/hooks/pre-commit (remove the .sample)

NOTE: It is usually a better idea to actually rename the sample file rather than create a new file and name it pre-commit because the permissions have to change. If you do decide to create a new file you need to update the permissions of it with chmod +x pre-commit. I haven't tried this and can't say it actually works so try at your own risk.

You should now have a pre-commit file inside of .git/hooks that contains the given hook.

You have added pre commit hooks to this project

Add the code for the hook to your already existing pre-commit file in .git/hooks

Hook

#!/bin/sh

pass=true
RED='\033[1;31m'
GREEN='\033[0;32m'
NC='\033[0m'

echo "Running Linters:"

# Run tslint and get the output and return code
tslint=$(npm run tslint)
ret_code=$?

# If it didn't pass, announce it failed and print the output
if [ $ret_code != 0 ]; then
	printf "\n${RED}tslint failed:${NC}"
	echo "$tslint\n"
	pass=false
else
	printf "${GREEN}tslint passed.${NC}\n"
fi

# Run stylelint and get the output and return code
stylelint=$(npm run stylelint)
ret_code=$?

if [ $ret_code != 0 ]; then
	printf "${RED}stylelint failed:${NC}"
	echo "$stylelint\n"
	pass=false
else
	printf "${GREEN}stylelint passed.${NC}\n"
fi

# If there were no failures, it is good to commit
if $pass; then
	exit 0
fi

exit 1

Outcome

Now whenever you run any form of git commit, it will run tslint and stylelint first.

On a failure: tslint and/or stylelint will output the failures and you will not be prompted to commit.

On a pass: tslint and stylelint will announce they have passed and you will be brought to the commit screen.