【发布时间】:2017-05-15 01:16:57
【问题描述】:
我正在研究重新格式化代码的预提交挂钩,一般来说,它可以工作;它会重新格式化和git adds 任何暂存文件,并且生成的提交包含所需的重新格式化的代码。
但是,它与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 是如何与索引交互以产生上面显示的结果吗?甚至更好的是,是否有办法让我的预提交钩子很好地发挥作用?
我的理解是 git commit --only 与工作树中的文件版本一起工作,所以我尝试从 pre-commit 挂钩中删除 git add 步骤以查看会发生什么,结果不正确 -正在提交的文件的格式化版本和工作树中正确格式化的文件(这符合我对标准git commit 的期望,但我不确定在git commit --only 的上下文中会发生什么)。
我知道可以使用clean 过滤器来重新格式化代码,而不是使用预提交挂钩,但是这种方法会引入一些情况复杂性,如果可能的话最好避免。
注意:此问题与Phpstorm and pre commit hooks that modify files 有关,但重点是解决git commit --only 上下文中的问题。此外,JetBrains 似乎没有解决该问题,正如该问题的已接受答案中所建议的那样。
【问题讨论】:
-
关于预提交对 git 提交行为的影响的更多信息:stackoverflow.com/a/7230886/6309
标签: git githooks jetbrains-ide