如何强制 git pre-commit 钩子对翻译文件也做 flake8 检查?
解读
在 OpenStack 社区,翻译文件(*.po) 默认被 flake8 忽略,因为它们是自动生成的。然而国内私有云交付团队往往会对 po 文件做二次加工(拼接品牌词、插入日志占位符),一旦混入 Python 语法错误会导致 Horizon 启动时报 TemplateSyntaxError,线上事故屡见不鲜。面试官问“强制”二字,是在考察候选人能否:
- 识别 flake8 的默认过滤规则
- 在不破坏社区兼容性的前提下,把 po 文件重新纳入扫描范围
- 保证 CI 与本地 pre-commit 行为一致,且性能可接受
知识点
- flake8 的 --filename 参数:支持正向/反向通配,决定哪些路径被送入 pyflakes/pycodestyle
- pre-commit 框架的 exclude 与 types 字段:exclude 优先级高于 files,types 可精确到 file 级别
- po 文件语法:msgstr 里允许出现 Python 3 的 {} 占位符,但禁止未闭合的引号、括号
- 国内镜像加速:tox -e pep8 里常把 flake8 源换成清华或阿里,避免外网超时导致 CI 失败
- OpenStack 社区约定:po 文件由 Zanata 自动生成,任何手动修改必须在 commit message 加 Translation-Update-Forced 标签,否则会被 zuul 打回
答案
- 在项目根目录创建
.pre-commit-config.yaml,显式覆盖 flake8 的默认排除列表:
repos:
- repo: https://github.com/pycqa/flake8
rev: 5.0.4
hooks:
- id: flake8
# 1. 先清空社区默认的 exclude
exclude: ^$
# 2. 再用 files 把 *.po 加回来
files: \.(py|po)$
# 3. 只跑语法错误,忽略行长度
args: ['--select=E9,F63,F7,F82', '--filename=*.po']
- 本地安装并强制生效:
pip install pre-commit
pre-commit install --hook-type pre-commit --overwrite
git config --local core.hooksPath .git/hooks
-
验证:故意在 po 文件里写
msgstr "未闭合串,执行git commit -a -m "test",应触发 F630: unclosed string,提交被阻断即达标。 -
若仓库仍保留旧版
tox -e pep8,需在tox.ini里同步追加:
[testenv:pep8]
deps = -c{env:UPPER_CONSTRAINTS_FILE:https://releases.openstack.org/constraints/upper/master}
flake8
commands = flake8 --select=E9,F63,F7,F82 --filename=*.py,*.po .
如此既满足社区 CI,又保证国内交付场景下 po 文件不再成为隐形炸弹。
拓展思考
- 性能权衡:po 文件动辄上万行,全量跑 flake8 会拖慢开发者笔记本。可在 pre-commit 里再加
entry: bash -c 'git diff --cached --name-only --diff-filter=AM | grep -E "\.po$" | xargs flake8 --select=E9,F63,F7,F82',仅扫描被修改的 po 文件,把耗时从 30 s 降到 3 s。 - 多语言占位符冲突:中文翻译里常出现 “{} 项目” 被误报 F523,可写一小段 poflake8 插件 跳过含 msgctxt="django" 的行,保持零误报。
- 与 zuul gate 保持一致:把上述 flake8 命令封装成
tools/flake8-wrap.sh,在.zuul.yaml的 pep8 job 里调用同一脚本,避免“本地能过、gate 却挂” 的尴尬。