Skip to content

Instantly share code, notes, and snippets.

@tehviking
Forked from jeremywrowe/gist:5373873
Last active December 16, 2015 04:48
Show Gist options
  • Save tehviking/5379449 to your computer and use it in GitHub Desktop.
Save tehviking/5379449 to your computer and use it in GitHub Desktop.
Extract into class & methods and add ability to enter argument to specify branch
#!/usr/bin/env ruby
class Go
attr_accessor :branch_input, :branch_list
def initialize
@branch_input = ARGV[0]
end
def initialize_branch_name(&block)
@branch_input ||= begin
yield if block_given?
print "\n> "
gets.strip
end
end
def run
run_git_command
initialize_branch_name do
output_help
branch_listing
end
select_branch
end
def output_help
puts <<-MSG
You can use the number to the left of the branch name or
an ignorant best match guess can be made to select the branch
string that you type in.
MSG
end
def run_git_command
@branch_list ||= `git for-each-ref --count=10 --sort=-committerdate refs/heads/ --format='%(refname:short)'`.split("\n")
end
def branch_listing
branch_list.each_with_index do |branch, index|
puts "#{index}) #{branch}"
end
end
def select_branch
if branch_input =~ /^\d+$/
`git checkout #{branch_list[branch_input.to_i]}`
else
closest_matches = branch_list.select{|branch| branch.downcase.include? branch_input.downcase }
if closest_matches.size > 0
`git checkout #{closest_matches.first}`
else
puts "Did not find a branch name that included #{branch_input.downcase}"
end
end
end
end
trap("INT") { puts "\ncatch'ya later"; exit 0 }
Go.new.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment