Skip to content

Instantly share code, notes, and snippets.

@whylom
Last active December 17, 2015 19:49
Show Gist options
  • Save whylom/5662939 to your computer and use it in GitHub Desktop.
Save whylom/5662939 to your computer and use it in GitHub Desktop.
Ruby script that enhances the standard `git branch` listing by organizing and color coding remotes (origin, root, etc).

This is a Ruby script that enhances the standard git branch listing by organizing and color coding remotes (origin, root, etc).

screenshot

  • Branches whose remote is origin (the default) are listed at the top.
  • Branches whose remote is not origin are listed next, with the remote displayed in magenta. This makes it easier to see branches that are shared with other developers.
  • A hardcoded list of staging branches are displayed at the bottom in gold.
require 'colorize'
module Git
class Branch
attr_accessor :name, :remote
STAGING = %w(master staging test).freeze
def self.all
@@branches ||= all!
end
def self.all!
@@branches ||= []
@@branches.clear
raw = `git branch -vv | tr -d '*' | tr -s ' '`.gsub(/^\s/, '').split("\n")
@@branches = raw.map do |line|
Git::Branch.new(
:name => line.split(' ').first,
:remote => line[/\[([\w]+)\//, 1]
)
end
end
def self.current
@@current ||= current!
end
def self.current!
@@current = `git symbolic-ref HEAD 2>/dev/null`.gsub('refs/heads/', '').chomp
end
def self.by_remote(remote)
all.select { |b| b.remote == remote }
end
def self.origin
by_remote('origin')
end
def self.root
by_remote('root') - staging
end
def self.staging
all.select(&:staging?)
end
def self.fork
all.select { |b| b.remote != 'origin' && b.remote != 'root' }
end
def self.print
Git::Branch.origin.each(&:print)
Git::Branch.root.each(&:print)
Git::Branch.fork.each(&:print)
Git::Branch.staging.each(&:print)
end
def initialize(params)
@name = params[:name]
@remote = params[:remote] || 'origin' # if branch hasn't been pushed to a
end # remote, assume remote == "origin"
def current?
name == self.class.current
end
def staging?
@staging || STAGING.include?(name)
end
def origin?
remote == 'origin'
end
def root?
remote == 'root'
end
def fork?
!(origin? || root?)
end
def to_s
"#{name} [#{remote}]"
end
def print
name = if current?
"* #{self.name.colorize(:green)}"
elsif staging?
" #{self.name.colorize(:yellow)}"
else
" #{self.name}"
end
remote = if !staging? && !origin?
"[#{self.remote.colorize(:magenta)}]"
else
nil
end
puts [name, remote].compact.join(' ')
end
end
end
Git::Branch.print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment