Pre-commit hooks getting partial committed file list
-
29-06-2021 - |
Question
I know running git-diff and other tools can identify the changes in the repository, but when I do a partial commit, I need to pass only the committed files (rather than the entire set of files that are touched) to the pre-commit hook.
For example, I modified three files and commit only two, and I want the pre-commit hook to know the name of the two files.
git status --porcelain
M A.c
M B.c
M C.h
then I execute:
git commit -m "two files only" A.c B.c
How can the pre-commit hook get hold of the list of the two files only?
Solution
The pre-commit is run at the beginning of the commit process... @Vince's link is the one to look at. Once the hook is running, your script can use git diff --cached --name-only
to get the names of the staged files within the pre-commit script. The command works even if the user had staged more for commit, but only requested to commit a subset of the files on the command line.
OTHER TIPS
I think your question is more : when is the pre-commit hook triggered?
And [I just discovered hooks, it seems cool] apparently, pre-commit hook is triggered before you even run git commit
(you can still try to hook up a "Hello World" script to it to see precisely when it is triggered).
But then what I can think of is the add command : git add -u A.c B.c
(u stands for update). Once you've run it, commit command will commit these files (just run git commit -m mymessage
)
I don't know exactly how you can retrieve the list of added files (via the index probably), but hopefully this will help you
Reference : http://git-scm.com/book/en/Customizing-Git-Git-Hooks