Git 提交推送报 error: failed to push some refs pre-receive hook declined 排查
分析 Git 远端推送被 pre-receive 钩子拒绝的根本诱因,排查大文件拦截、分支保护与敏感凭证泄露规则。
故障现象
开发者在执行 git push origin main 时,代码被服务端强制拒收并抛出错误:
remote: GitLab: You are not allowed to push code to protected branches on this project.
remote: error: hook declined to update refs/heads/main
To https://gitlab.example.com/org/repo.git
! [remote rejected] main -> main (pre-receive hook declined)
error: failed to push some refs to 'https://gitlab.example.com/org/repo.git'
本地 commit 无法推送到远程仓库。
核心机制与根因分析
pre-receive 是运行在 Git 服务端(如 GitLab、GitHub Enterprise、Gerrit)上的特权服务器端钩子:
- 执行阶段:在客户端发送对象但服务端正式更新 ref 引用之前触发,若钩子返回非 0 退出码,推送事务直接被整体丢弃。
- 常见拒绝原因:
- 分支保护规则(Branch Protection):当前用户角色为 Developer,目标分支设为仅 Maintainer 允许直接 push;
- 单文件体积超标(File Size Limit):历史 commit 中意外打入了超过 100MB 的大文件,触发了服务端的强行拦截;
- 敏感凭据探测拦截(Secret Push Protection):提交的代码中被扫描到了明文私钥或 API Token;
- 强制推送被禁(Force Push Disabled)。
针对性解决方案
方案一:检查并剥离误提交的超大文件(若因文件超限)
如果是因为某次历史提交不慎包含了大文件,必须使用 git-filter-repo 重写历史剥离大文件,而不能简单提交一个 git rm:
# 彻底从历史中抹除大文件
git filter-repo --invert-paths --path path/to/large_file.zip
git push origin main --force
方案二:新建特性分支并发起 Merge Request / Pull Request
如果受分支保护规则约束,严禁直接推送主分支,应推送新分支并走标准的代码审查流程:
git checkout -b feature/user-auth
git push origin feature/user-auth


