Quick tip on Git diffs for PHP files

igorsantos07 profile image Igor Santos Updated on ・1 min read

Every time a PHP developer runs git diff on the command line a kitten dies:

Badly-hunked PHP diff
Hell no! This piece of code is inside a method, not the class :(

Those @@ snippets are called Hunk Headers - because every part of a diff is called a hunk, duh. Unfortunately, git is too stupid to figure out PHP files should be diff'd according to PHP syntax, so you need to give it a hand by using a rule on git attributes.

Unfortunately(2), git attributes are not that easy to configure user-wide as config options are (no git global commands), thus here's the tip:

  1. create the folder if it doesn't exist: ~/.config/git (or whatever is in $XDG_CONFIG_HOME)
  2. write in ~/.config/git/attributes this: *.php diff=php
  3. Save and diff away

This can also be configured per project by adding the same text inside a .gitattributes file.

Well-hunked PHP diff
There you have it! A decent Hunk Title on PHP files

It's quite weird why Git doesn't understand out of the box that through the file extension, as there are pre-baked settings to understand several syntaxes (such as TeX, Fortran, HTML, etc). Go figure!


Posted on by:

igorsantos07 profile

Igor Santos


Remote developer with ~10 years of experience. Mostly worked with PHP and with a passion for REST APIs and front-end interfaces, UX and DX. I also have a foot on React and Python/Django :)


O PHPRio é o grupo de todas as pessoas que participam da comunidade PHP no estado do Rio de Janeiro. Todos contribuem, de diversas formas, para a organização de nossos eventos e divulgação do PHP em terras fluminenses.


markdown guide