Skip to content

Instantly share code, notes, and snippets.

@joey-g
Last active April 23, 2021 17:22
Show Gist options
  • Save joey-g/ea48b100ba6a158e98903c3a081d6b5d to your computer and use it in GitHub Desktop.
Save joey-g/ea48b100ba6a158e98903c3a081d6b5d to your computer and use it in GitHub Desktop.
Git Branch Pruning Utility
def get_all_branches
value = `git branch --list`
value.split("\n")
end
def parse_branch_name(branch_name_line)
branch_name_line.match(/^(\*\s)?(\s{2})?(.*)$/i).captures.last
end
def print_branch_names(branch_names)
branch_names.each_with_index { |line, index| puts "(#{index}) '#{line}'"}
puts
end
def delete_branches(all_branch_names, indexes_to_keep = [])
all_branch_names.each_with_index { |branch_name, index|
next if indexes_to_keep.include? index
default_branches = ['master', 'main', 'develop']
current_branch_name = branch_name.strip
next if current_branch_name.include? '*'
next if default_branches.include? current_branch_name
parsed_branch_name = parse_branch_name branch_name
`git branch -D #{parsed_branch_name}`
puts "Deleted #{parsed_branch_name}" if $?.exitstatus == 0
}
end
def get_additional_branches_to_keep
done = false
indexes = []
begin
puts 'Select another branch to keep, or <enter> to submit entries...'
index_input = get_index_input
if index_input == -1
done = true
else
indexes.push index_input
end
end while not done
indexes
end
def get_index_input
index = nil
index_input = nil
begin
begin
index_input = gets.chomp
if index_input == 'a'
index = -1
elsif index_input.empty?
index = -2
else
index = Integer(index_input)
end
rescue
puts "Invalid index seletion: #{index_input}"
end
end while index.nil?
index
end
def shutdown
puts 'Exiting: Branch pruning complete'
exit 0
end
if __FILE__ == $PROGRAM_NAME
all_branches = get_all_branches
puts "---Branch Pruning Utility---"
puts "(master/main/develop/current branches preserved by default)"
print_branch_names all_branches
puts "Select a branch index to keep, 'a' to delete all, or <enter> to exit..."
branch_to_keep_index = get_index_input
if branch_to_keep_index == -2
puts "No branches selected"
shutdown
end
if branch_to_keep_index == -1
delete_branches all_branches
shutdown
end
branch_indexes_to_keep = get_additional_branches_to_keep
all_branch_indexes_to_keep = branch_indexes_to_keep.unshift(branch_to_keep_index)
delete_branches all_branches, all_branch_indexes_to_keep
shutdown
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment