tzi tzi - 1 month ago 5x
Git Question

Git: How to re-stage the staged files in a pre-commit hook

I'm writting a git pre-commit hook.

The script could reformat some code, so it could modify the staged files.

How can I re-stage all files that are already staged ?

tzi tzi

Without the pre-commit hook context, you can get a list of the staged files with the following command:

git diff --name-only --cached

So if you want to re-index the staged files, you can use:

git diff --name-only --cached | xargs -l git add

In the pre-commit hook context, you should follow the advices of David Winterbottom and stash unstaged changes before anything else.

This technique allows you not to be worry about indexing, or alterate, a change that was not staged. So you don't have to stage all the staged files, but all the updated files:

# Stash unstaged changes
git stash -q --keep-index

# Edit your project files here

# Stage updated files
git add -u

# Re-apply original unstaged changes
git stash pop -q