2

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.

Ryan Price
  • 315
  • 6
  • 17

1 Answers1

2

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.stack.imgur.com/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".

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Thanks for getting me on the right track, but I'm not quite there. Filters seem to expect stdin and write to stdout. If I want to format only the file(s) being committed how would I go about doing that? %f says it would pass the filename through, but the docs immediately after state that filters expect stdin and stdout. So given all this, how do apply my vim command to the specific file(s) being committed? – Ryan Price Nov 27 '17 at 21:05
  • @RyanPrice "If I want to format only the file(s) being committed how would I go about doing that?": that is what a clean script does: it only formats files about to be committed. From there, see if you cannot pass the content to a vim command, as in https://vi.stackexchange.com/a/5994 – VonC Nov 27 '17 at 21:47