Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I conditionally activate the Git prompt depending on the repository I'm in?

I'm using the built-in git prompt shell script to improve my Bash prompt.

. ~/git-completion.bash
. ~/git-prompt.sh

export GIT_PS1_SHOWDIRTYSTATE=1
export GIT_PS1_SHOWUNTRACKEDFILES=1
export GIT_PS1_SHOWUPSTREAM="auto"
export GIT_PS1_SHOWCOLORHINTS=1

I have this one enormous enterprise application repository (100s of thousands of files, a very deep directory tree, the .git directory is almost 2 GB). The prompt is taking a very long time to complete.

Is there some way to tell git-prompt.sh to ignore this workspace? Either by flags or in my .bashrc?

like image 269
Anthony Mastrean Avatar asked Mar 30 '15 20:03

Anthony Mastrean


1 Answers

Define a conditional Git prompt

Take a look at the suggested Bash prompt definition in git-prompt.sh (but without the user and host, because they take too much space, and are irrelvant to your question):

PS1='[\W$(__git_ps1 " (%s)")]\$ '

Nothing prevents you from inserting a test in the command substitution, like so:

PS1='[\W$(if true; then __git_ps1 " (%s)"; fi)]\$ '

although this example is rather silly. Using this idea, you can define a conditional Git prompt such that,

  • if you're outside the working tree of the offending repo, the Git prompt is activated, and
  • if you're inside the repo in question, the Git prompt is deactived.

The following Bash prompt definition does exactly that:

export PS1='[\W$(if [[ ! $PWD/ = $OFFENDINGDIR/* ]]; then __git_ps1 " (%s)"; fi)]\$ '

where OFFENDINGDIR is a variable that must be assigned the path to the root directory of the offending repo.

Example

Assume that ~/projectA is the offending repo. For information, here is my default prompt definition:

PS1='\W\$ '

Very simple; no Git prompt whatsoever. Now, let's cd to the offending repository:

~$ cd projectA

# Let's check that we are indeed in a Git repo:
projectA$ git branch
* master

# Now let's set up our conditional Git prompt:
projectA$ export OFFENDINGDIR=$PWD
projectA$ export PS1='[\W$(if [[ ! $PWD/ = $OFFENDINGDIR/* ]]; then __git_ps1 " (%s)"; fi)]\$ '

# Our Bash prompt changes accordingly...
[projectA]$
# ... but notice that it contains no branch info (as desired).

# However, if we cd to another repo...
[projectA]$ cd ../projectB
[projectB (master)] $
# ... the Git prompt is there, as desired!
like image 50
jub0bs Avatar answered Sep 30 '22 02:09

jub0bs