Reputation: 141150
This question is based on the thread.
I have the following Git-prompt at the moment.
I get the following warning after cd
ing to a non-Git folder.
fatal: Not a git repository (or any of the parent directories): .git
fatal: git diff [--no-index] takes two paths
fatal: Not a git repository (or any of the parent directories): .git
fatal: git diff [--no-index] takes two paths
My current code for Git-prompt in Zsh
# get the name of the branch we are on
git_prompt_info() {
ref=$(git symbolic-ref HEAD | cut -d'/' -f3)
echo $ref
}
get_git_dirty() {
git diff --quiet || echo '*'
}
autoload -U colors
colors
setopt prompt_subst
PROMPT='%{$fg[blue]%}%c %{$fg_bold[red]%}$(git_prompt_info)$(get_git_dirty)%{$fg[blue]%} $ %{$reset_color%}'
The problem is the following code which causes the warning for non-Git folders
get_git_dirty() {
git diff --quiet || echo '*'
}
I tried to solve the bug by redirecting errors to /tmp/ unsuccessfully such that
get_git_dirty() {
git diff --quiet 2>/tmp/error || echo '*' 2>/tmp/error
}
How can you get rid of the warning messages for non-git directories?
Upvotes: 3
Views: 2002
Reputation: 323454
Use
REL=$(git rev-parse --show-prefix 2>/dev/null) || { echo "$@" ; exit ; }
or
BR=$(git symbolic-ref HEAD 2>/dev/null) || { echo "$@" ; exit ; }
Exit early.
To be more explicit: you can't use exit status of git diff --quiet
to check whether you are in working repository because git diff then "exits with 1 if there were differences and 0 means no differences." (see git-diff manpage)
Upvotes: 2
Reputation: 141150
I get this code finally to work:
# get the name of the branch we are on
git_prompt_info() {
BR=$(git symbolic-ref HEAD 2>/dev/null | awk -F/ '{ print $3 }') || { echo "$@" ; exit ; }
echo $BR
}
while the rest are the same as before.
Upvotes: 0
Reputation: 37267
Actually, I think it's the first one that's causing the error because when I run it in a non-git directory, I get the errors. The second one doesn't spit out the errors.
You could redirect the error output to /dev/null
.
This would work in bash, not sure about zsh but it should give you an idea of how to go.
git_prompt_info() {
ref=$(git symbolic-ref HEAD 2>/dev/null)
if [ ! -z $ref ]; then
newref=$(echo $ref | cut -d'/' -f3)
echo $newref
fi
}
I don't know what would be more expensive though, running git or traversing all the directories until you find a .git directory. Git probably does the directory traversal anyways. Not sure.
Upvotes: 2
Reputation: 6128
Would something like this work?
get_git_dirty() {
set __MT_OK__=0
if [[ -d .git ]]; then
__MT_OK__=1
fi
while [[ ! -d .git ]]; do
cd ..
if [[ -d .git ]]; then
__MT_OK__=1
break
fi
if [[ $PWD = "/" ]]; then
break
fi
done
if [[ __MT_OK__ -eq 1 ]]; then
git diff --quiet || echo '*'
fi
}
This may not be the most elegant solution, but it should work.
Upvotes: 1