在 devcontainer 中让 VS Code UI 提交触发 post-commit 钩子
结论:VS Code 的源代码管理界面没有单独的 post-commit 钩子开关。UI 提交最终仍由 git commit 完成,post-commit 由 Git 执行。所以,遇到钩子没反应时,先检查 devcontainer 中 VS Code 的 Git 扩展与终端使用的 Git、仓库目录、core.hooksPath 或非交互环境是否一致。钩子也可能已经执行,只是输出被隐藏;或者 latexmk 因 PATH 问题失败。git hook run post-commit 只能说明脚本在终端里能跑,不能说明 UI 提交时的环境相同。
先用日志确认是否执行
在钩子里记录工作目录、PATH 和 latexmk 位置,再从 VS Code UI 提交一次,然后检查日志文件。不要只看 UI 有没有显示 echo 输出。
#!/bin/sh
#.git/hooks/post-commit
LOG=/tmp/post-commit.log
{
date
echo "PWD=$(pwd)"
echo "PATH=$PATH"
command -v latexmk || true
} >> "$LOG" 2>&1
if find . -maxdepth 1 -name '*.tex' -print -quit | grep -q .; then
latexmk -f -g >> "$LOG" 2>&1
fi
如果日志没生成,说明 UI 提交没有走到这个钩子路径;如果日志生成了,但 latexmk 报错,优先修 PATH 和工作目录。
检查 VS Code 使用的 Git
打开命令面板运行 Git: Show Git Output,查看实际执行的 git commit 命令和工作目录。也可以在 devcontainer 终端执行:
command -v git
git --version
在 devcontainer 或工作区设置中把 git.path 固定为容器内 Git 的实际路径,例如:
{
"git.path": "/usr/bin/git"
}
路径以 command -v git 输出为准,不要直接照抄。如果写进 .devcontainer/devcontainer.json,可以放在 customizations.vscode.settings 下。修改后执行 Developer: Reload Window。
检查钩子路径和权限
在终端确认钩子位置和 core.hooksPath:
git config --get core.hooksPath
git rev-parse --git-path hooks/post-commit
chmod +x "$(git rev-parse --git-path hooks/post-commit)"
如果 core.hooksPath 不为空,钩子要放在该目录下;默认的 .git/hooks 不再适用。使用 worktree 时,也以 git rev-parse --git-path hooks/post-commit 的结果为准。
让钩子适配非交互环境
VS Code 从 UI 提交时通常是非交互环境,PATH 可能比终端短。可在钩子里显式补充 latexmk 所在目录:
#!/bin/sh
#.git/hooks/post-commit
PATH="/path/to/latexmk/bin:$PATH"
export PATH
if command -v latexmk >/dev/null 2>&1; then
latexmk -f -g
else
echo "latexmk not found in PATH" >&2
fi
把 /path/to/latexmk/bin 换成终端中 dirname "$(command -v latexmk)" 的实际结果。如果项目里的 .tex 不在仓库根目录,find . -maxdepth 1 也可能找不到目标文件,需要按实际目录调整。
注意事项
post-commit是提交完成后执行的;如果提交本身失败,它不会运行。- UI 中看不到 echo 输出,不代表钩子没运行;用日志判断更可靠。
- 如果日志显示钩子没被调用,而 Git 输出、
core.hooksPath和git.path都正常,可以先重载窗口,确认 Git 扩展在容器内启用。仍不行时,作为排查手段,可临时在容器终端里执行git commit完成提交,同时保留日志和 Git 输出,方便继续定位。 - 不要在钩子里依赖交互式 shell 配置;显式设置 PATH 和绝对路径更稳。
备注:内容仅供参考。
