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

前端 未结 2 1365
南旧
南旧 2021-02-04 02:37

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

2条回答
  •  礼貌的吻别
    2021-02-04 03:19

    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
    

提交回复
热议问题