You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IntelliJ结合WSL2使用pre-commit提交失败,提示未找到pre-commit

问题描述

通过命令行提交代码时pre-commit hooks工作正常,但使用IntelliJ IDE提交失败,报错信息如下:

0 file committed, 2 files failed to commit: dummy commit pre-commit not found. Did you forget to activate your virtualenv?

已确认virtualenv处于激活状态。


补充信息1

系统为Ubuntu 20.04.4 LTS,执行以下命令的输出:

  • grep ^INSTALL .git/hooks/pre-commit → INSTALL_PYTHON=/home/lioriz/anaconda3/envs/py36/bin/python
  • which pre-commit → /home/lioriz/anaconda3/envs/py36/bin/pre-commit
  • head -1 $(which pre-commit) → #!/home/lioriz/anaconda3/envs/py36/bin/python
  • pre-commit --version → pre-commit 2.17.0

补充信息2

.pre-commit-config.yaml 配置

# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v3.2.0
    hooks:
    -   id: trailing-whitespace
    -   id: end-of-file-fixer
    -   id: check-yaml
    -   id: check-added-large-files

.git/hooks/pre-commit 脚本

#!/usr/bin/env bash
# File generated by pre-commit: https://pre-commit.com
# ID: 138fd403232d2ddd5efb44317e38bf03

# start templated
INSTALL_PYTHON=/home/lioriz/anaconda3/envs/py36/bin/python
ARGS=(hook-impl --config=.pre-commit-config.yaml --hook-type=pre-commit)
# end templated

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.  Did you forget to activate your virtualenv?' 1>&2
    exit 1
fi

执行test -x /home/lioriz/anaconda3/envs/py36/bin/python; echo $?输出0

补充信息3

IntelliJ运行在Windows 11系统上,使用WSL2,pre-commit安装在WSL2的Ubuntu 20.04.4 LTS环境中


解决方法

问题出在IntelliJ通过WSL2执行Git操作时,未加载正确的环境上下文,导致pre-commit无法被识别。可按以下步骤修复:

  • 配置IntelliJ使用WSL环境的Git
    打开File > Settings > Version Control > Git,将Path to Git executable设置为WSL中的Git绝对路径,例如\\wsl$\Ubuntu-20.04\usr\bin\git,确保IDE调用的是WSL内的Git,而非Windows本地版本。

  • 让IntelliJ终端使用WSL环境
    进入File > Settings > Tools > Terminal,将Shell path设置为C:\Windows\System32\wsl.exe,这样IDE内的终端会直接进入WSL环境,保证环境变量和虚拟环境的上下文一致。

  • 修改pre-commit钩子脚本,强制指定路径
    编辑.git/hooks/pre-commit脚本,调整判断逻辑,优先使用pre-commit的绝对路径:

    # 替换原有的if-elif-else块
    if [ -x "/home/lioriz/anaconda3/envs/py36/bin/pre-commit" ]; then
        exec "/home/lioriz/anaconda3/envs/py36/bin/pre-commit" "${ARGS[@]}"
    elif [ -x "$INSTALL_PYTHON" ]; then
        exec "$INSTALL_PYTHON" -mpre_commit "${ARGS[@]}"
    else
        echo '`pre-commit` not found.  Did you forget to activate your virtualenv?' 1>&2
        exit 1
    fi
    
  • 检查Git提交配置
    进入File > Settings > Version Control > Commit,确保Run git hooks选项处于勾选状态,避免IDE跳过钩子执行。


内容的提问来源于stack exchange,提问作者lior.i

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:15:34