问题
So I know this question have been asked a lot, but I don't find any suitable answers. I'm looking to display the name of the current git rev in my prompt, but in a pretty way : if I'm on a branch, I want the name of the branch; if it's not a branch, I'd like the relative name (ie master~2
) in my prompt.
At first, I was using something like what you can see here. It worked well : I had the name of the branch, or the rev SHA1 number. Then I moved to an approached based on git name-rev
, which was great at first, but then I noticed that the name was mixed up sometimes : after merging master
into staging, on both branches I had master
in my prompt. Given how much I rely on this, I can't have this. But having master~2
instead of a SHA1 number was really great.
So I hope there's a way to combine both approaches. If it's possible to display the tag name too, I'll take it (though I don't use them much - yet). And the top would be to have git only commands, no looking up git internal files -- they could change at some point.
Thanks for reading!
回答1:
Taken from zsh-git repository: https://github.com/jcorbin/zsh-git/blob/master/functions/zgitinit#L70
name=$(git symbolic-ref -q HEAD)
if [ $? -eq 0 ]; then
if [[ $name == refs/(heads|tags)/* ]]; then
name=${name#refs/(heads|tags)/}
fi
else
name=$(git name-rev --name-only --no-undefined --always HEAD)
if [ $? -ne 0 ]; then
return 1
elif [[ $name == remotes/* ]]; then
name=${name#remotes/}
fi
fi
You may also consider using zsh :)
回答2:
Here's a bash version of the zsh answer. I tried to leave it as a comment, but I can't post code blocks in comments. :P
name=$(git symbolic-ref -q HEAD)
if [[ -n "$name" ]]; then
name="${b#refs/heads/}"
else
name=$(git name-rev --name-only --no-undefined --always HEAD)
name="${name#tags/}"
name="${name#remotes/}"
fi
回答3:
Take a look at git describe:
git describe HEAD --all --long
You can tweak it around with other options and get some nice information. If you use it with the --tags option you get the distance in commits from the latest found tag, e.g.
$ git describe HEAD --tags
1.1-4-g860832e
In my example it shows that we are four commits ahead of the tag 1.1. It also displays the sha1 hash at the end after the 'g', in this case it means the short hash is 860832e
来源:https://stackoverflow.com/questions/9752619/get-pretty-git-rev-name