Reputation: 157324
I have a git controlled directory (actually my home directory) within which there are ignored directories (e.g. trash space, and directories controlled by other VCSs). I want to be able to have my bash prompt show whether a directory is version controlled and if so by which VCS, but e.g. git rev-parse
will always find the topmost .git
directory.
Is there a way to ask git whether I'm in an untracked directory?
I've found this to work:
if ! git rev-parse 2>&/dev/null; then
echo "not in git"
else
PREFIX=$(git rev-parse --show-prefix)
if [ -z "$PREFIX" ]; then
echo "at git top level"
elif [ -z $(cd $(git rev-parse --show-toplevel); \
git ls-files -o --directory "${PREFIX%%/}")
echo "tracked by git"
else
echo "untracked"
fi
fi
However it seems very hackish and brittle. Is there a better way?
Upvotes: 4
Views: 598
Reputation: 9323
For the question of ignored folders specifically, you can use git check-ignore
and test the error code.
$ cd ~/project
$ git check-ignore tracked-folder
$ echo $?
1
$ git check-ignore ignored-folder
ignored-folder
$ echo $?
0
Untracked folders appear to have the same behavior as tracked (but not ignored) folders. Adding a -v
will show you which rules make the folder (or file) ignored.
Upvotes: 2
Reputation: 38694
git clean -nd
approach: If it is ignored directory, then git clean -d
wants to remove it, so it is easy way to check status of current directory.
if git clean -xnd `pwd` | grep 'Would remove \./' > /dev/null; then
echo "Inside ignored or untracked directory"
else
echo "Inside normal directory"
fi
Tweak git clean
to change rules about untracked files. Checked in my $HOME repository.
Note: don't experiment with git clean
without -n
lightly, it can clear things from your home.
Upvotes: 5
Reputation: 84343
You can use bash_completion and a modified PROMPT_COMMAND. It worked for me in casual testing, but if it breaks you own both pieces. :)
# Add this to your shell startup file (e.g. ~/.bashrc).
export PS1
export PROMPT_COMMAND='
if fgrep -q "${PWD/\/home\/$LOGNAME\/}" ~/.gitignore; then
PS1="${debian_chroot:+($debian_chroot)}\u@\h:\w$(__git_ps1) [ignored]\$ "
else
PS1="${debian_chroot:+($debian_chroot)}\u@\h:\w$(__git_ps1)\$ "
fi'
To make this work, you'll need to make sure all your ignored paths are listed relative to your home directory, and be sure to test it out before relying on it to protect you from any destructive operations like rm -rf
.
Upvotes: -1