Prepend Git commit message with partial branch name

别等时光非礼了梦想. 提交于 2019-12-02 22:20:24

Ok, first, this:

BRANCH_NAME=$(git branch 2>/dev/null | grep -e ^* | tr -d ' *')

is major overkill :-) Use:

branch=$(git symbolic-ref --short HEAD) || ...

to get the current branch name. The part after || is "what to do if you're not on a branch" (i.e., if you're in "detached head" mode)—you'll have to decide that for yourself. (Your current code sets BRANCH_NAME to the empty string; to do that, you don't even need the || part, but you may want to add -q, or a 2>/dev/null, to avoid the "fatal:" message from symbolic-ref.)

The rest is just basic scripting. In bash you can use regex's directly, in old sh you can invoke expr or sed. Both sed and tr can upper-case-ify, but sed can do a regex too, so it looks like a good candidate:

$ trimmed=$(echo $branch | sed -e 's:^\([^-]*-[^-]*\)-.*:\1:' -e \
    'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/')
$ echo $trimmed
TICKET-45

Last, it's slightly dangerous to do:

echo "some stuff $(cat $1)" > $1

as you're depending on the shell to expand the $(cat $1) before it truncates the output file for the > $1 part. (Obviously it works, but you're subject to shell vagaries.) Better to use a temporary file, or maybe another sed but in-place:

sed -i .bak -e "1s:^:[$trimmed] :" $1
# or use -i '', but note minor warning in sed man pages

The above is only tested piecemeal, but should work.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!