Skip to content

Instantly share code, notes, and snippets.

@jpowell
Created November 20, 2012 00:36
Show Gist options
  • Save jpowell/4115175 to your computer and use it in GitHub Desktop.
Save jpowell/4115175 to your computer and use it in GitHub Desktop.
list and clear branches match a prefix
#! /usr/bin/ruby
class BranchList < Struct.new(:name_prefix)
require 'set'
COMMANDS = {
:remote => {
:list => 'git remote show origin',
:remove => 'git push origin :%s'
},
:local => {
:list => 'git branch',
:remove => 'git branch -D %s'
}
}
def initialize(*args)
@branches = Hash.new { |h, k| h[k] = Set.new }
@removed = Hash.new { |h, k| h[k] = Set.new }
super
end
def print(scope)
get_branches(scope)
if @branches[scope].any?
puts "Listing all #{scope} branches"
@branches[scope].each { |br| puts "\t#{br}" }
else
puts "There are no #{scope} branches that match that prefix"
end
puts
end
def remove(scope)
get_branches(scope)
puts "Removing all #{scope} branches"
@branches[scope].each do |branch|
next if @removed[scope].include?(branch)
system( COMMANDS[scope][:remove] % branch )
end
end
private
def get_branches(scope)
return unless @branches[scope].empty?
grep_output = `#{COMMANDS[scope][:list]} | grep #{name_prefix}`
grep_output.each_line do |line|
@branches[scope].add( line.match(/(#{name_prefix}[^\s]*)/)[0] )
end
end
end
if __FILE__ == $0
if branch_prefix = ARGV.first
list = BranchList.new(branch_prefix)
list.print(:remote)
list.print(:local)
else
$stderr.puts 'You must specify the prefix of a branch name.'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment