如何让VS Code自动在提交信息文本框前置分支名?
Absolutely! You can absolutely set up VS Code to auto-prefix your commit messages with the current branch name—no more manually typing that ID every time. Here are two solid ways to do it, depending on whether you prefer a quick extension-based solution or a native Git hook setup:
1. Use a VS Code Extension (Quick & Easy)
My go-to for this is the Branch Commit Prefix extension. It does exactly what you want: detects your current branch, pre-fills the commit message box with [branch-name]: , and puts the cursor right after the space so you can start typing immediately.
- To set it up:
- Open the Extensions panel (Ctrl+Shift+X on Windows/Linux, Cmd+Shift+X on Mac)
- Search for "Branch Commit Prefix" and install it
- That's it! The default settings work perfectly for your use case. If your branches have extra prefixes (like
feature/ID-7345), you can tweak the extension's regex settings to extract just theID-xxxxpart.
2. Use a Git Hook (Native, No Extensions)
If you'd rather avoid extensions, you can use Git's built-in prepare-commit-msg hook to achieve the same result. Here's how:
- Navigate to your project's
.git/hooksfolder (you might need to enable hidden files to see it) - Copy the
prepare-commit-msg.samplefile and rename it toprepare-commit-msg(remove the.samplesuffix) - Open the new
prepare-commit-msgfile in VS Code and replace its contents with this script:
#!/bin/sh # Grab the current branch name BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD) # Optional: Extract just the ID part if your branch has a prefix (e.g., feature/ID-7345 → ID-7345) # Remove this line if your branch name is already just the ID BRANCH_NAME=$(echo "$BRANCH_NAME" | sed -E 's/.*(ID-[0-9]+)/\1/') # Only add the prefix if the commit message is empty (initial state) if [ -z "$(cat "$1")" ]; then echo "$BRANCH_NAME: " > "$1" # Set cursor position right after the prefix (requires Git 2.27+) echo "# cursor: $((${#BRANCH_NAME} + 2))" >> "$1" fi
- Save the file, then open your terminal and run this command to give it execution permissions:
chmod +x .git/hooks/prepare-commit-msg
Now whenever you open VS Code's commit panel, the message box will auto-populate with your branch name followed by : , and the cursor will be ready for you to type your commit details.
If your branch naming convention is different (e.g., bugfix/ID-123), just adjust the sed line in the script to match your pattern—you can tweak the regex to capture exactly the part you want as the prefix.
内容的提问来源于stack exchange,提问作者zmii

