3

The current branch name convention looks like this:

feature/NEU-123 

I try to create a git hook to prepend a commit message, that the commit looks like this:

NEU-123: commit message 

I have no experience in creating scripts like this. That's why I don't have a starting point and need to try out your approaches.

I've looked up a few Stackoverflow entries but I can't find anything about this specific naming convention. Also it would be great, if I am on the master branch, or any branch with just a single word branch name, that the complete branch name is prepended.

Already thanks for your help.

3
  • It's not a good idea. A commit is not bound to a specific branch. Why would you like to do so? Commented May 18, 2021 at 7:12
  • Because I need to identify the commit to a specfic branch. And it is hard to do so, if the branch is merged into the master branch. Each branch is bound to an issue. Commented May 18, 2021 at 7:14
  • @ElpieKay: in this case, it's not such a bad idea as the branch name was deliberately created to match an issue number in some sort of issue-tracking system. (I prefer to put issue numbers into the commit message body rather than the header but different groups have different conventions...) Commented May 18, 2021 at 17:41

1 Answer 1

4

As mentioned in Client-side hook / Committing-Workflow Hooks, a prepare-commit-msg could be used in conjunction with a commit template to programmatically insert information.

Example: janniks/prepare-commit-msg which does get the branch name (using Ruby, but you can use any scripting language you want):

# get the current branch name git_branch_command = "git rev-parse --abbrev-ref HEAD" branch_name, error, result = Open3.capture3(git_branch_command) 

Same idea in ljpengelen/prefix-commit-message

Close to what you are looking for: mikhailsidorov/husky-prepare-commit-msg-example, and its bash .githooks/prepare-commit-msg, from Mikhail Sidorov:

Example project with prepare-commit-msg hook configured to prepend branch name to commit message automatically

#!/bin/bash COMMIT_MSG_FILE=$(echo $1 | head -n1 | cut -d " " -f1) if [ -z "$BRANCHES_TO_SKIP" ]; then BRANCHES_TO_SKIP=(master develop test) fi BRANCH_NAME=$(git symbolic-ref --short HEAD) BRANCH_NAME="${BRANCH_NAME##*/}" BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$") BRANCH_IN_COMMIT_MSG=$(head -1 $COMMIT_MSG_FILE | grep -c "$BRANCH_NAME") if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && ! [[ $BRANCH_IN_COMMIT_MSG -ge 1 ]]; then sed -i'.bak' -e "1s/^/$BRANCH_NAME /" $COMMIT_MSG_FILE fi 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.