我们正在使用 pre-commit.com为我们的 python 项目配置预提交 Hook 的框架。当暂存一组文件进行提交时,应将预提交 Hook 应用于存储库的状态,其中包含/修改这些已暂存的文件,而不应包含对未暂存文件的所有修改。这对于被修改的文件很有效,但对于新文件/未跟踪的文件不起作用。如果我创建一个新文件并修改一些现有文件,然后只想将更改提交到已修改的文件,而不是(尚未)提交到新文件,则预提交 Hook 也会应用于新文件。这通常会导致钩子(Hook)失败,因为应用钩子(Hook)的存储库的状态不一致。
在应用 Hook 时,是否有任何配置选项/命令行参数可以预先提交以从存储库中排除未跟踪的文件?
除了暂时从存储库中删除新文件之外,还有其他方法可以解决此问题吗?
我已经尝试将新文件标记为要使用 git add -N <new_file>
提交,这没有帮助,但会导致警告:
[WARNING] Unstaged intent-to-add files detected.
预提交版本:2.10.1
示例:
考虑一个包含以下内容的 git 存储库:
|-- .git
|-- .pre-commit-config.yaml
`-- foo
`-- existing_file.py
文件 foo/existing_file.py
所在位置内容如下:
# cat foo/existing_file.py
a = 1 + 1
预提交 Hook 已通过以下方式安装:
pre-commit install
预提交 Hook 配置为运行 flake8:
# cat .pre-commit-config.yaml
default_language_version:
python: python3.8
default_stages: [commit]
repos:
- repo: local
hooks:
- id: flake8
name: flake8
entry: flake8
always_run: true
files: $^
language: system
现在,我对文件 foo/existing_file.py
进行了更改并添加了新文件 foo/new_file.py
。经过这些更改后,文件具有以下内容:
# cat foo/existing_file.py
a = 1 + 2
# cat foo/new_file.py
import math
现在,我想提交对 foo/existing_file.py
所做的更改,但不是新的/未跟踪的文件 foo/new_file.py
。所以,我登台foo/existing_file.py
,而foo/new_file.py
仍未被追踪。
# git add foo/existing_file.py
# git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: foo/existing_file.py
Untracked files:
(use "git add <file>..." to include in what will be committed)
foo/new_file.py
如果我现在尝试提交,flake8 在文件 foo/new_file.py
中返回错误,它不包含在提交中:
# git commit
flake8...................................................................Failed
- hook id: flake8
- exit code: 1
./foo/new_file.py:1:1: F401 'math' imported but unused
最佳答案
您的配置绕过框架并始终在所有文件上运行。在这种情况下,预提交只是做你告诉它做的事情
我的建议是不要像您正在使用的那样使用 always_run
(而且您的 files: $^
最好写成 pass_filenames: false
)
该框架的 Gist 之一是它只将必要的文件传递给您的工具,因此您只需检查已 checkin 的内容,当您删除该功能时,您现在会检查存储库中的所有内容(甚至是那些已 checkin 的内容)未 checkin )
使用 flake8 的推荐方法是通过以下配置:
- repo: https://github.com/PyCQA/flake8
rev: 3.9.0
hooks:
- id: flake8
免责声明:我创建了预提交,并且我是 flake8 当前的主要维护者
关于git - 如何通过 pre-commit.com 从预提交 Hook 中排除未跟踪/新文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66965977/