In my job we are doing continuous integration by using Atlassian's Bamboo (you can use any other product like Travis CI).
That means that the code is automatically deployed to a server and the test suite is continuously running.
That means that if you mess up something when committing code, everyone will get an informative email, the error will be registered and your stats will get worse. What a pity!
Specially if you are in a rush, there is the probability of forgetting to run the tests before committing the code (I've just changed a line, won't break anything), so the best way to NEVER commit anything bad is to automate this process.
Also, if you are using pull requests and the code is being reviewed (as we are doing in the team I work) you would probably want to follow some coding style guidelines. There is always also the probability of doing a bad indentation, or writing a loop or a conditional in a freestyle way, not spacing operators or any other little detail you don't pay attention to, but is not following the style conventions and it's difficult to read for other people. This should also be automated so you don't have to manually check it all the time, and you ensure that only good code is going to end up on your repo.
Git offers some hooks for executing scripts at several times in the usual git flow, you can find them in the
.git/hooks folder of your git project. You can check your folder as it's already populated with many example scripts, very informative and easy to understand.
From now it depends on your project characteristics to decide what hooks are you going to use and what actions you going to write in those hooks. In my case, as we are writing PHP code, using PHPUNIT for testing and following a custom fork of the PSR-2 ruleset. I will be writing the following in the pre-commit hook:
#!/bin/bash files_modified="$(git diff-index --name-only HEAD)" for f in $files_modified; do if [[ $f == *.php ]]; then ~/.composer/vendor/bin/phpcs --standard=OurCustomRuleset $f fi done phpunit
The first line is going to pick the filename of the files that I've locally edited. Then for every of those files, if it contains PHP code (by checking it's extension). I'll be running PHP Code Sniffer using our custom ruleset, if there is any coding style problem it will be displayed on the screen.
Once every edited file is checked, then phpunit is run to ensure all the test are passing and the code is safe to commit.
Note that even if any of those process fail, the execution will continue and you will finally be taken to the commit message step, from now it's up to you to continue committing the code by writing a commit message and saving the file or you want to close the editor to fix the problems that were displayed and try to commit again.
For automatically fix the code style issues, as it can be very tedious I use a vim plugin called vim-php-cs-fixer that will automatically fix those errors.