简体   繁体   中英

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)?

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, eg, http://newartisans.com/2009/02/building-a-better-pre-commit-hook-for-git/ .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM