Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Git prompt for Bash
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
# The methods that get called more than once are memoized.
# original:
# https://github.com/benhoskings/dot-files/blob/master/files/bin/git_cwd_info
$RESET = "\e[0m" # reset
$BLACK = "\e[0;30m"
$RED = "\e[0;31m"
$GREEN = "\e[0;32m"
$BROWN = "\e[0;33m"
$BLUE = "\e[0;34m"
$PURPLE = "\e[0;35m"
$CYAN = "\e[0;36m"
$LIGHT_GREY = "\e[0;37m"
$DARK_GREY = "\e[1;30m"
$LIGHT_RED = "\e[1;31m"
$LIGHT_GREEN = "\e[1;32m"
$YELLOW = "\e[1;33m"
$LIGHT_BLUE = "\e[1;34m"
$LIGHT_PURPLE = "\e[1;35m"
$LIGHT_CYAN = "\e[1;36m"
$WHITE = "\e[1;37m"
$HI_CYAN = "\e[0;96m"
$_BLACK = "\e[40m"
$_RED = "\e[41m"
$_GREEN = "\e[42m"
$_YELLOW = "\e[43m"
$_BLUE = "\e[44m"
$_PURPLE = "\e[45m"
$_CYAN = "\e[46m"
$_WHITE = "\e[47m"
def git_repo_path
@git_repo_path ||= `git rev-parse --git-dir 2>/dev/null`.strip
end
def in_git_repo
!git_repo_path.empty? &&
git_repo_path != '~' &&
git_repo_path != "#{ENV['HOME']}/.git"
end
def git_parse_branch
rv = RUBY_VERSION.split('.')
rvf = "#{rv[0]}.#{rv[1]}.".to_f
f = File.read("#{git_repo_path}/HEAD").strip
if rvf >= 1.9
f.strip.split(/.*?(?>refs\/heads\/)(.*)$/).last
else
f.strip.split(/.*?(?>refs\/heads\/)(.*)$/)
end
end
def git_head_commit_id
`git rev-parse --short HEAD 2>/dev/null`.strip
end
def git_cwd_dirty
"" unless git_repo_path == '.' || `git ls-files -m`.strip.empty?
end
def git_commit_count
if not `git st`.scan(/by (\d+) commit/).empty?
" #{$WHITE}%d→#{$RESET}" % `git st`.scan(/by (\d+) commit/).first.first
end
end
def git_untracked_files
" +" unless `git st`.scan(/Untracked files/).empty?
end
def rebasing_etc
if File.exists?(File.join(git_repo_path, 'BISECT_LOG'))
"+bisect"
elsif File.exists?(File.join(git_repo_path, 'MERGE_HEAD'))
"+merge"
elsif %w[rebase rebase-apply rebase-merge ../.dotest].any? {|d| File.exists?(File.join(git_repo_path, d)) }
"+rebase"
end
end
if in_git_repo
print "\n[#{$RED}#{git_parse_branch}#{$RESET} #{$DARK_GREY}@#{$RESET} #{$LIGHT_BLUE}#{git_head_commit_id}#{$RESET}#{$_BLACK}#{$WHITE}#{rebasing_etc}#{$RESET}#{$DARK_GREY}#{git_cwd_dirty}#{$RESET}#{$LIGHT_CYAN}#{git_untracked_files}#{$RESET}#{git_commit_count}]"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.