You need to enable JavaScript to run this app. Python pre-commit能否将子目录设为项目运行基座?
优惠活动
大模型
产品
解决方案
定价
更多

Python pre-commit能否将子目录设为项目运行基座?

pre-commit 运行工作目录定位问题

当前仓库结构

myrepo/
      .git
      tool1/  
           src/main.py
           tests/test.py
           .pre-commit-config.yaml

现有pre-commit配置

repos:
- repo: local
  hooks:
    - id: pytest-cov
      name: pytest coverage
      stages: [push]
      language: system
      entry: pwd  # 原始 entry 为:pytest testtool --cov --cov-fail-under=0 
      types: [python]
      pass_filenames: false

实际遇到的问题

  • 为了验证pre-commit运行上下文的基础目录,临时将hook的entry修改为pwd
  • 在myrepo/tool1目录下执行pre-commit run --hook-stage=push --verbose命令时,pwd的输出结果为myrepo(Git仓库根目录),而非预期的myrepo/tool1
  • 由于项目内所有路径均基于tool1目录设置,需要让pre-commit的运行基础目录指向myrepo/tool1
  • 需要确认是否存在对应配置项或运行方式可以实现该目标,还是要求项目必须放置在Git仓库根目录下才能正常使用pre-commit

可行的调整方案

首先明确pre-commit的固定设计逻辑:pre-commit 从核心设计上就会将Git仓库的根目录作为所有hook的默认运行工作目录,没有内置配置项可以直接修改该默认行为。
不需要将项目强行迁移到Git仓库根目录,可以通过以下方式适配现有目录结构:

  • 在hook的entry命令中显式添加工作目录跳转逻辑,适配跨系统运行:
    • Linux/macOS 环境下,可将entry修改为 bash -c "cd tool1 && pytest tests --cov --cov-fail-under=0"
    • Windows 环境下,可将entry修改为 cmd /c "cd tool1 && pytest tests --cov --cov-fail-under=0"
  • 由于当前hook配置了pass_filenames: false,不会依赖传入的文件路径参数,在命令内部跳转工作目录的方式完全兼容现有逻辑,不需要调整hook的其他配置。
  • 若需要测试跳转后的目录定位是否符合预期,可临时将entry替换为对应系统的目录跳转+pwd命令,验证输出结果是否为myrepo/tool1即可。

内容的提问来源于stack exchange,提问作者inger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.17 20:06:02