寻求Windows环境下检查Jira Issue Key的Pre-commit Hook编写帮助
Hey there! I totally get how overwhelming Git hooks can feel when you're new to scripting—let's walk through this step by step so you can get your Jira key check up and running smoothly on Windows.
First, a quick clarification: To validate commit messages, we'll use a commit-msg hook (not a pre-commit hook, which runs before you stage files). This hook triggers right after you write your commit message but before the commit is finalized—perfect for our needs.
Step 1: Locate Your Git Hooks Folder
In your Git project, navigate to the hidden .git folder, then go into the hooks subfolder. You’ll see sample files like commit-msg.sample—we’ll be creating/modifying a file called commit-msg (no .sample or .txt extension allowed!).
Step 2: Create the Commit-Msg Script
Open Notepad (or your favorite text editor) and paste this batch script. I’ve added comments to explain each part so you can follow along easily:
@echo off setlocal enabledelayedexpansion :: Grab the path to the commit message file that Git passes to the hook set "COMMIT_MSG_FILE=%~1" :: Read the first line of the commit message (the main subject line) set "COMMIT_SUBJECT=" for /f "delims=" %%a in (%COMMIT_MSG_FILE%) do ( set "COMMIT_SUBJECT=%%a" goto :check_subject ) :check_subject :: Check if the subject line matches a standard Jira Issue Key pattern (e.g., PROJ-1234) :: The regex looks for one+ uppercase letters, a dash, then one+ numbers echo !COMMIT_SUBJECT! | findstr /r "^[A-Z]*-[0-9]*" > nul :: If no match is found, block the commit and show an error if %errorlevel% equ 1 ( echo. echo ERROR: Your commit message is missing a valid Jira Issue Key (e.g., PROJ-1234) echo Please update your commit message to include the key at the start. exit /b 1 ) :: If we reach here, the key was found—allow the commit to proceed exit /b 0
Save this file as commit-msg (make sure to set "Save as type" to "All Files" in Notepad so it doesn’t add an unwanted .txt extension).
Step 3: Test the Hook
Let’s verify it works as expected:
- Try committing without a Jira key:
You’ll see an error message, and the commit will be blocked.git commit -m "Fix login button alignment issue" - Now try a valid commit message:
This should go through without any problems!git commit -m "PROJ-456 Fix login button alignment issue"
Quick Customization Tips
- If your Jira project keys follow a strict format (e.g., exactly 3 uppercase letters), adjust the regex in the
findstrline. For example:^[A-Z][A-Z][A-Z]-[0-9]* - If you want to check the entire commit message (not just the first line), remove the
goto :check_subjectline so the script reads all lines of the message.
内容的提问来源于stack exchange,提问作者Help required

