2011年9月16日 星期五

在terminal中顯示git branch


之前在網路上閒看文章時曾經發現過這麼一個小功能:
在terminal中直接顯示所在資料及的git branch與上次commit時間。

一開始只是覺得新鮮好玩,而是在開始使用不同branch後,才發現這還真的是蠻有用的!
顯示git branch可以避免commit時不小心push或pull錯地方,
顯示上次commit時間則是可以提醒自己,該commit一下了XD

陸續試了幾種方式,底下是目前使用的方式,
還算容易理解,而且實際效果看起來也還算舒爽!


1. in terminal:
$ vi ~/.bashrc

2. in ~/.bashrc
at the end of the file:

a. define the function that show the git branch of current directory:
function git_branch {
ref=$(git symbolic-ref HEAD 2> /dev/null) || return;
echo "("${ref#refs/heads/}") ";
}

b. define the function that show the last commit time of the current directoty:
function git_since_last_commit {
now=`date +%s`;
last_commit=$(git log --pretty=format:%at -1 2> /dev/null) || return;
seconds_since_last_commit=$((now-last_commit));
minutes_since_last_commit=$((seconds_since_last_commit/60));
hours_since_last_commit=$((minutes_since_last_commit/60));
minutes_since_last_commit=$((minutes_since_last_commit%60));
echo "${hours_since_last_commit}h${minutes_since_last_commit}m ";
}

c. define the bash prompt(就是PS1, 也就是terminal顯示的樣子):
function proml {
local LIGHT_BLUE1="\[\033[1;34m\]"
local LIGHT_BLUE2="\[\033[1;35m\]"
local LIGHT_GRAY="\[\033[0;37m\]"
local LIGHT_WHITE="\[\033[1;0m\]"
case $TERM in
xterm*)
TITLEBAR='\[\033]0;\u@\h:\w\007\]'
;;
*)
TITLEBAR=""
;;
esac

PS1="${TITLEBAR}\
$LIGHT_BLUE1[$LIGHT_WHITE\W$LIGHT_BLUE1]\
$LIGHT_BLUE2\$(git_branch)\
$LIGHT_GRAY\$(git_since_last_commit)\
$LIGHT_WHITE\$ "
PS2='> '
PS4='+ '
}
proml


2.c的部分,前半段在定義顏色,如果有玩過BBS的可能就會大概知道;
中間的xterm其實我不是很懂,因為這是網路抄下來的code然後再自己調整,而這部份因為不懂就沒有去動它。
後面PS1的地方,就是在定義新的terminal前面的顯示方式。
/W就是顯示目前所在資料夾名稱,如果想要顯示絕對路徑,可以使用/w。
不過我讓她只顯示目前資料夾就好,如果需要絕對路徑,那就再用pwd來顯示就好。
而git_branch,git_since_last_commit就是前面定義的兩個function,
然後最後面就是呼叫proml這隻function。


最後顯示結果就會類似這樣:
[~](alpha-version) 17h51m $
以上!

沒有留言:

張貼留言