0

Hi I want to create a default message from branch name. I know we can use hook to do this but I get some problem with grep function.

For exmaple, if our branch name is "test-1234-my-first-feature', how can I convert it into "[test-1234]"?

I think this is pure shell script question, can some help?

we can get branch and by this How to add Git's branch name to the commit message?

BRANCH=`git branch | grep '^\*' | cut -b3-`
FILE=`cat "$1"`
echo "$BRANCH $FILE" > "$1"
Community
  • 1
  • 1
NewPlayerX
  • 47
  • 1
  • 9
  • so you want to get the two first words on a slash-based string? – fedorqui Jun 30 '15 at 16:27
  • Is the question here how to get just those first two `-` delimited fields? Will the branch name always look like that? Will there always be two fields you care about or can there be more? – Etan Reisner Jun 30 '15 at 16:39
  • 1
    You're better off getting the branch name with plumbing: `BRANCH=$( git rev-parse --abbrev-ref HEAD )` – William Pursell Jun 30 '15 at 17:02

1 Answers1

0

Something like this added to your prepare-commit-msg will do the job:

#!/usr/bin/env sh

# prepend a task number to a commit message automatically

# if amend, don't do anything
if ! [ -z $3 ] ;then
    exit
fi

branch=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD)
task_number=$(echo $branch | cut -d - -f1-2)

if [ -z $task_number ] ;then        # when task has not been retrieved from branch name, exit
    exit
fi

# enclose task number in square brackets
text=[${task_number}]

sed -i "1s/^/$text \n/" $1
Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38
  • Thanks for the help. The code is working but sed doesn't work so that I am using `echo` instead. Another small question, If I have branch name like `Feature/test-1234-sadf`, how can I cut `Feature/` out? Thx – NewPlayerX Jul 02 '15 at 15:12
  • `how can I cut Feature/ out` - well asked, use `cut` command: `echo Feature/test-1234-sadf | cut -d / -f 2` – Arkadiusz Drabczyk Jul 02 '15 at 15:16
  • When I do `git commit`, it gives a `sed: 1: ".git/COMMIT_EDITMSG": invalid command code .` – NewPlayerX Jul 13 '15 at 19:07