简体   繁体   中英

Extract portion of branch name for prepare commit message in Git

I want to prepend every commit message with a portion of my branch name. For example lets say my branch naming convention is the following:

issueType/repoName-issueNumber --> bug/myRepo-123

I want my commit message to go from

added missing semicolon

to

myRepo-123 : added missing semicolon

So far in my prepare-commit-msg file I have the following but it is printing out the entire branch name

#!/bin/sh
NAME=$(git branch | grep '*' | sed 's/* //')
STORY_NUMBER=$(echo $NAME | sed 's/.*\(myRepo-[0-9]\+\.log\).*/\1/')
echo "$STORY_NUMBER" : $(cat "$1") > "$1"

... renders ...

bug/myRepo-123 : added missing semicolon

What edits do I need to make to the regex to extract everything AFTER / ?

Thanks

I ended up finding a really great question and answer that helped me solve my problem. It can be found here https://unix.stackexchange.com/questions/24140/return-only-the-portion-of-a-line-after-a-matching-pattern

In the end this was my script which prints out myRepo-123: commit message

#!/bin/sh
BRANCH_NAME=$(git symbolic-ref --short HEAD)
STORY_NUMBER=$(echo $BRANCH_NAME | sed -n -e 's/^.*\(myRepo-\)/\1/p')
echo "$STORY_NUMBER": $(cat "$1") > "$1"

Before I explain how I modified the regex it's worth noting that I found an easier way to get my current branch name using the --short flag on the symbolic ref command.

The following is taken from the other stack exchange answer for the regex

Detailed explanation:

  • -n means not to print anything by default.
  • -e is followed by a sed command. s is the pattern replacement command.
  • The regular expression ^. stalled: matches the pattern you're looking for, plus any preceding text (. meaning any text, with an initial ^ to say that the match begins at the beginning of the line). Note that if stalled: occurs several times on the line, this will match the last occurrence.
  • The match, ie everything on the line up to stalled:, is replaced by the empty string (ie deleted).
  • The final p means to print the transformed line.
  • If you want to retain the matching portion, use a backreference: \\1 in the replacement part designates what is
    inside a group (…) in the pattern. Here, you could write
    stalled: again in the replacement part; this feature is useful
    when the pattern you're looking for is more general than a simple string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM