如何让pre-commit仅对修改文本而非整个文件应用修复?
问题描述
我们计划在API模型上使用typos工具搭建拼写检查机制,但部分API模型已正式发布,修改已发布接口中的拼写错误并不合适,仅需对新增的变更内容进行拼写检查。请问是否可以配置pre-commit使其仅对修改的文本内容而非涉及的整个文件应用修复操作?
补充说明:当前.git/hooks/pre-commit的内容是pre-commit install生成的默认版本,代码如下:
#!/usr/bin/env bash # Get python from environment: INSTALL_PYTHON=$(command -v python3 || command -v python) ARGS=(hook-impl --config=.pre-commit-config.yaml --hook-type=pre-commit) HERE="$(cd "$(dirname "$0")" && pwd)" ARGS+=(--hook-dir "$HERE" -- "$@") if [ -x "$INSTALL_PYTHON" ]; then exec "$INSTALL_PYTHON" -mpre_commit "${ARGS[@]}" elif command -v pre-commit > /dev/null; then exec pre-commit "${ARGS[@]}" else echo "'pre-commit' not found, install it with 'pip install pre-commit'!" 1>&2 exit 1 fi
解决方案
完全可以实现,不需要修改默认的pre-commit钩子脚本,只需要在.pre-commit-config.yaml里配置typos钩子的参数,让它只针对Git暂存区的变更内容处理:
- 配置typos增量检查钩子
在你的.pre-commit-config.yaml中添加或修改typos的配置:
repos: - repo: https://github.com/crate-ci/typos rev: v1.16.0 # 换成你想用的最新版本号 hooks: - id: typos args: [--diff, --write-changes] stages: [pre-commit]
参数说明:
--diff:让typos只扫描Git暂存区里修改过的内容(基于diff结果)--write-changes:只修复变更部分的拼写错误,不会碰文件里已发布的原有内容
- 验证效果
- 对已发布的API文件做局部修改,故意加个拼写错误
- 用
git add把修改暂存 - 触发pre-commit钩子(直接提交或者手动跑
pre-commit run typos),你会发现只有新增的错误被修复,旧内容里的拼写错误完全不动
- 额外选项
如果你不想自动修复,只需要检查并阻止错误提交,去掉--write-changes参数就行,钩子会在变更内容里发现拼写错误时拦截提交。
内容的提问来源于stack exchange,提问作者Peter Silon
相关产品推荐
相关产品推荐

