git and shell prompt

C. Boemann cbo at boemann.dk
Sat Dec 18 21:52:11 GMT 2010


On Thursday 16 December 2010 09:54:04 Cyrille Berger Skott wrote:
> Hi,
> 
> Yesterday I have introduced the commands related to branches, and I am
> expecting that really soon we will all be working with multiple branch. The
> problem is to remember in which branch you are at the moment, of course you
> can run "git branch" and you will know. But frankly, you are going to
> commit to the wrong branch more than once, unless the name of the branch
> is screamed in your face.
> 
> But with bash and zsh, it is possible to have the name of the current
> branch in the prompt (you can have other things, but for me the branch
> name is what is interesting).
> 
> For zsh, I added this to my .zshrc :
> 
> 
> #
> # VCS support
> #
> 
> autoload -Uz vcs_info
> 
> precmd() {
>   psvar=()
>   vcs_info
>   [[ -n $vcs_info_msg_0_ ]] && psvar[1]="$vcs_info_msg_0_"
> }
> 
> PS1VCS=%(1v.%F{yellow}%1v%f.)
> 
> 
> And then you just need to add $PS1VCS to your PS1 line. For instance, mine
> looks like this:
> 
> export PS1="%B%F{cyan}%T%f %F{red}%n%f%F{%{$(echo -n 
'\e[1;33m')%}@%f%m
> %F{green}%~%f$PS1VCS%F{%{$(echo -n '\e[1;33m')%}%%%f%b "
> 
> 
> And I get this in my calligra prompt:
> 9:53 cyrille at navis
> ~/Projects/kde4/src/calligra/krita/plugins/extensions/dockers
> (git)-[master]-%
> 
> (with some colors :) )
> 
> I am no user of bash, but here is an example of how to achieve the same
> result: http://glandium.org/blog/?p=170 .
The code in that link didn't quite work out for me, so here is what it looks 
like for me after I've worked on it (add it to .bashrc and make sure PS1 is 
not reset afterwards):

  local vcs base_dir sub_dir ref
  sub_dir() {
    local sub_dir
    sub_dir=$(readlink -f "${PWD}")
    sub_dir=${sub_dir#$1}
    echo ${sub_dir#/}
  }

 git_dir() {
    base_dir=$(git rev-parse --show-toplevel 2>/dev/null) || return 1
    sub_dir=/$(git rev-parse --show-prefix)
    sub_dir=${sub_dir%/}
    ref=$(git symbolic-ref -q HEAD || git name-rev --name-only HEAD 
2>/dev/null)
    ref=${ref#refs/heads/}
    vcs="git"
  }

 git_dir ||
 base_dir="$PWD"

 echo "${base_dir/$HOME/~}${vcs:+[$ref]${sub_dir}}"
}

PS1='${debian_chroot:+($debian_chroot)}\u@\h:$(__vcs_dir)\$ '



More information about the calligra-devel mailing list