Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git pre-commit hook code formatting with partial commit?

is there a way to have a pre-commit hook which auto-formats the code (for example with astyle) but does not destroy a partial commit?

Workflow:

# edit a file.txt
git add -p file.txt
# add one chunk, but not another

git commit -m 'a message'
[PRE_COMMIT_HOOK] Formatting source code

git status
# the "another" chunk is still not added

My problem is, that if you do a git add inside the pre-commit hook, which is required after the script formatted the source code, adds the "another" chunk, too. But I don't want that.

Is there a way to achieve this?

like image 960
musicmatze Avatar asked Apr 04 '14 09:04

musicmatze


Video Answer


1 Answers

I'd do this by doing the work with the low-level "plumbing" commands, my first attempt would be something along the lines of

git ls-files --stage \*.c | while read mode object stage path; do
case $mode in
10*)
      formatted=`git show $object | indent | git hash-object -w --stdin`
      git update-index --cacheinfo $mode $formatted "$path"
;;
esac
done

To avoid redundant processing, start from git diff-index --name-only --diff-filter=AM output as @torek suggests.

like image 61
jthill Avatar answered Sep 26 '22 21:09

jthill