I’m working on a project(PHP) and on every commit there are some breaks on code convention. I’m using git for version control. Is there a way for automated code formatting so that all the code stays clean?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are two parts to the question: automatically formatting the code, and detecting when it doesn’t conform to your coding standards.
Automatically formatting the code is not really something you want to put inbetween you and your repo directly. Modifying files, or attempting to modify files, in a
pre-commithook is likely to make a mess. As such it doesn’t matter what vcs you are using.Using a tool to format the code via your editor or as a process you run (manually, or semi-automated) as part of your development workflow would be appropriate. For example, vim has the
=function to auto-indent code, and as mentioned by others Pear’s beautifier is one possibility to do this.Detecting code standard devitions requires a cli tool that tells you when a file does not conform to coding standards – the obvious choice is PHP Code Sniffer (phpcs) – though it could simply be the same tool you use to beautify your code manually (if you use one) and checking that it doesn’t change the file contents.
You may need to write your own standard to use with phpcs if none of the existing standards match your style.
You can use a pre-commit hook to trigger a check on the code right before you commit it – If there are code errors found, you’ll be notified about them and the commit aborted. You can bypass your pre-commit hooks using
git commit --no-verifyYou may find this repo useful: https://github.com/AD7six/git-hooks
Example:
(commit aborted, code does not meet code standards)
(commit succeeded – even though code standards were not met)