Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git pre-commit hook: getting list of changed files

I am developing validation and linting utility to be integrated with various commit hooks, including Git one

https://github.com/miohtama/vvv

Currently validators and linters are run against the whole project codebase on every commit. However, it would be much more optimal to run them against changed files only. For this, I would need to know changed files list in my Git precommit hook (in Python)

https://github.com/miohtama/vvv/blob/master/vvv/hooks/git.py

What options I have to extract the changed files list (in Python if that matters)?

like image 682
Mikko Ohtamaa Avatar asked Apr 15 '12 14:04

Mikko Ohtamaa


2 Answers

This is not a direct answer to this - but I came across this when searching for a similar solution for JavaScript with npm.

With some further searching I believe this is now a solved problem for npm with the lint-staged library. This will lint only the staged files.

The problem I had when searching is that I was always searching for "pre-commit" hook linting rather than "staged file" linting. So I'm putting this answer here for anyone like me who comes here searching for a JavaScript solution.

Hopefully also the npm package can be of some inspiration to the Python world.

like image 88
icc97 Avatar answered Sep 25 '22 16:09

icc97


The pre-commit hook is a bit of a pain, if you really want to make things work "right", because what's in the work tree is not necessarily the same as what is to be committed:

$ echo morestuff >> file1; echo morestuff >> file2
$ git add file1 # but not file2
$ git commit -m 'modified two files but check in just one'

You can use git diff-index --cached HEAD to get a list of "what's about to be checked-in". See also, e.g., http://newartisans.com/2009/02/building-a-better-pre-commit-hook-for-git/.

like image 26
torek Avatar answered Sep 25 '22 16:09

torek