0

I'm trying to run a format command on code before it's committed. I ether want it to not allow commit if unformatted or automatically do it before committing.

What happens now is the commit happens and the formatting is applied after the commit as unstaged changes.

Here is my .git/hooks/pre-commit:

#!/bin/bash

go fmt src/*.go
Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
  • 1
    Your script will be formatting your working tree files before the commit. (pre-commit does mean what it says.) Your problem is that this is irrelevant to your commit which just carries on committing what was already staged. Not that this solves your main problem. – Ian Miller Dec 19 '17 at 18:14

2 Answers2

3

After formatting, add the files to the index:

#!/bin/bash

go fmt src/*.go
git add src/*.go
exit 0

It would probably be a good idea to mention this hook in your README. Just so you don't forget.

A possibly more serious point is that your edits to the code for this commit will be indistinguishable from go fmt changes.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
  • 2
    Note, though, that this will add all files matching `src/*.go` to the commit, including modifications to files already added, whether that was the original intention or not. – Tonio Dec 19 '17 at 19:57
  • also not, this will add files u may not have wanted in this particular commit. E.g. if u've modified file1 and file2, but only wanted to commit file1, this will commit both. – junvar Jul 16 '18 at 18:05
0

After reading Ian's code I had an idea which seems to be working.

#!/bin/bash

go fmt src/*.go
git add src/*.go
Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225