Search code examples
gitvimgithookspre-commit-hookpre-commit

Execute vim command as git pre-commit hook


I use the following command in vim to batch auto-format a specific filetype:

:args ~/someDirectory/**/*.filetype | argdo execute "normal gg=G" | update

I am trying to figure out how I would run this command as a pre-commit hook to ensure all files of the filetype I care about are auto-formatted before being committed.

How would I accomplish this?

Thanks in advance.


Solution

  • One solution would be, as in this answer, to call vim:

    files=`find /path/to/repo -name "*.filetype" -type f`
    for file in $files
    do
        vim -e -s -n "+normal gg=GZZ" $file
    done
    

    But, instead of using a pre-commit hook, you can define a clean script which will be executing a script (calling vim as above).

    The script is called through a content filter driver, using a .gitattributes declaration (in your case: *.filetype).

    https://i.sstatic.net/tumAc.png
    (image from "Customizing Git - Git Attributes" from "Pro Git book"))

    Once you declare that content filer driver in your local git config, it will automatically, on git commit, apply that script.

    See a complete example in "Best practice - Git + Build automation - Keeping configs separate".