Last active
May 15, 2022 00:31
-
-
Save maschwenk/a408f5bb195f48a70f1f8514677c0563 to your computer and use it in GitHub Desktop.
git recent branches
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# 1. put this in brew path `/usr/local/bin/` | |
# 2. make it executable `chmod +x /usr/local/bin/recent-branches` | |
# 3. in git config `~/.gitconfig` place an alias to the command inside `[alias]` block | |
# `br = recent-branches -n 20` (n being the number of branches you wanna show by default) | |
require 'optparse' | |
require 'English' | |
options = { number: 20 } | |
opt_parser = OptionParser.new do |opt| | |
opt.banner = 'Usage: receent-co [OPTIONS]' | |
opt.on('-n', '--number-of-branches NUMBER', 'number of branches to list') do |number| | |
options[:number] = number | |
end | |
opt.on('-h', '--help', 'help') do | |
puts opt_parser | |
exit | |
end | |
end | |
opt_parser.parse! | |
branches_without_markup = `git for-each-ref \ | |
--sort=-committerdate \ | |
--count=#{options[:number]} \ | |
refs/heads/ --format='%(refname:short)'` | |
abort('fatal: Failed to get branches') unless $CHILD_STATUS.success? | |
pretty_branches = `git for-each-ref \ | |
--sort=-committerdate \ | |
--count=#{options[:number]} \ | |
refs/heads/ \ | |
--color \ | |
--format='%(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(color:blue)%(authorname)%(color:reset) (%(color:green)%(committerdate:relative)%(color:reset))'` | |
abort('fatal: Failed to format branches') unless $CHILD_STATUS.success? | |
nums_appended = pretty_branches.split("\n").each_with_index.map do |x, index| | |
" #{index + 1}) " + x | |
end | |
puts nums_appended | |
begin | |
puts 'Enter a branch: ' | |
selected_branch = Integer(gets.chomp) - 1 | |
raise ArgumentError unless selected_branch.between?(0, nums_appended.length - 1) | |
branch_name_selection = branches_without_markup.split("\n")[selected_branch] | |
rescue ArgumentError | |
branch_name_selection = nil | |
puts 'Error: Please supply an integer branch number' | |
retry # retry on exception | |
rescue Interrupt | |
# suppress stack trace on ctrl+c | |
abort | |
end | |
system("git checkout #{branch_name_selection}") |
nicely done. I assume $CHILD_STATUS.success?
just checks if previous system call was successful
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With slightly improved error handling and mostly-appeased rubocop (because yes, I am that sort of person). I'd give you a pull request but, you know, gists so I have to
in comments instead.