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

如何在本地Git仓库强制实施提交签名以避免PR合并失败后返工?

Enforce Signed Commits Locally with Git Pre-Commit Hooks

Great question! You absolutely can enforce signed commits locally using Git's pre-commit hooks to block unsigned commits before they even get created, eliminating the need for tedious rebase cleanup later. Here's a step-by-step solution tailored to your workflow:

Step 1: Create the Pre-Commit Hook Script

Git hooks reside in your repository's .git/hooks directory. Create a file named pre-commit (no file extension) with the following script:

#!/bin/sh

# Check if commit signing is enabled
if ! git config --get commit.gpgSign | grep -q true; then
    echo "Git Error: Cannot commit without signature - Please enable commit signing with: git config commit.gpgSign true"
    exit 1
fi

# Verify a signing key is configured
SIGNING_KEY=$(git config --get user.signingkey)
if [ -z "$SIGNING_KEY" ]; then
    echo "Git Error: Cannot commit without signature - Please set your signing key with: git config user.signingkey <your-gpg-key-id>"
    exit 1
fi

# Proceed with the commit if checks pass
exit 0

Step 2: Make the Hook Executable

Run this command to grant execution permissions to the hook script:

chmod +x .git/hooks/pre-commit

Step 3: (Optional) Share the Hook With Your Team

Since the .git directory isn't tracked in Git, you can set up a shared hooks directory to distribute this rule to all team members:

  • Create a githooks folder at the root of your repository
  • Move the pre-commit file into this folder and commit it to the repo
  • Ask team members to run this command once after cloning the repo:
    git config core.hooksPath githooks
    

This tells Git to use hooks from the tracked githooks directory instead of the default .git/hooks, so everyone gets the enforcement automatically.

How It Works

When a user tries to commit without proper signing setup:

  • The hook checks if commit.gpgSign is set to true in their local Git config
  • It also verifies that a valid signing key (user.signingkey) is configured
  • If either check fails, it prints a clear error message and aborts the commit immediately, matching your desired outcome:
    Git Error: Cannot commit without signature - Please enable commit signing with: git config commit.gpgSign true
    

Quick Notes

  • Users will still need to set up their GPG keys locally (follow standard Git GPG signing setup instructions)
  • This local enforcement complements your GitHub branch protection rules, catching issues early instead of waiting for PR merge failures

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 19:22:30