我正在开发一个预先提交的钩子来重新格式化代码,并且通常它可以工作;它会重新格式化任何分阶段文件,并且结果提交包含所需的重新格式化代码。了解git commit - 只有和预先提交的钩子
但是,它不能很好地与git commit --only
(这是JetBrains IDE使用的变体)很好地玩,我试图理解为什么。 /的git commit --only
和组合pre-commit钩子导致不希望的索引工作树状态,如在下面的事件序列描述:
如果我使用格式错误的变化小到一个文件中,然后运行git status
,这是我所看到的:
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.php
no changes added to commit (use "git add" and/or "git commit -a")
如果我然后提交使用git commit --only -- file.php
,预提交钩子运行,并改变和重新格式化file.php
承诺。
但是,如果我然后再次运行git status
,这是结果(箭头标注矿):
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
(use "git push" to publish your local commits)
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: file.php <-- contains original change, improperly formatted
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.php <-- contains original change, properly formatted (per the most recent commit)
哪里上演新变化和来自的工作树的变化?
有人能够准确解释git commit --only
如何与索引交互以产生上面显示的结果 - 甚至更好,是否有办法让我的pre-commit钩子与它很好地搭配?
我的理解是,git commit --only
与工作树中的文件版本一起工作,所以我尝试从预提交钩子中删除git add
步骤以查看将会发生什么,并导致格式不正确的版本该文件被提交,并在工作树中正确格式化(这符合我对标准git commit
的期望,但我不确定在git commit --only
的上下文中会发生什么)。
我知道使用clean
过滤器重新格式化代码的可能性,而不是预先提交的钩子,但这种方法引入了一些情景复杂情况,如果可能的话很好避免。
说明:此问题与Phpstorm and pre commit hooks that modify files有关,但重点在于解决git commit --only
上下文中的问题。此外,JetBrains似乎也没有解决这个问题,正如在该问题的公认答案中所表明的那样。
关于更多关于预提交对git commit行为的影响:https://stackoverflow.com/a/7230886/6309 – VonC