Skip to content

Instantly share code, notes, and snippets.

@minrk
Last active June 11, 2019 14:25
Show Gist options
  • Save minrk/6126342 to your computer and use it in GitHub Desktop.
Save minrk/6126342 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#
# git fuzzy-checkout
# Same as `git checkout branch`, but with fuzzy matching if checkout fails.
# Turns `git checkout barnch` into `git checkout branch`,
# assuming `branch` is a branch.
# to use, you can alias:
# alias co="git fuzzy-checkout"
# co msater
require "set"
require "rubygems"
require "amatch"
def git_branches
# construct array of git branches
branches = `git branch -r`.split
remotes = Set.new `git remote`.split
branches.delete "*"
extras = []
# add remote branches minus the 'remote/' prefix
branches.each do |branch|
remote, branch = branch.split("/", 2)
if remotes.include? remote
extras.push branch
end
end
branches + extras
end
def fuzzy_checkout(branch)
# wrapper for git-checkout that does fuzzy-matching
#
# Helps with typos, etc. by automatically checking out the closest match
# if the initial checkout call fails.
# if checkout succeeds, nothing to do
success = system "git checkout #{branch}"
if success
return success
end
branches = git_branches.sort { |a,b|
branch.levenshtein_similar(a) <=> branch.levenshtein_similar(b)
}
best = branches.last
similarity = branch.levenshtein_similar(best)
if similarity > 0.5
puts "Best match for #{branch}: #{best} (#{(100 * similarity).round(1)}%)"
success = system "git checkout #{best}"
end
success
end
exit fuzzy_checkout(ARGV[0])
@minrk
Copy link
Author

minrk commented Jul 31, 2013

The same thing in Python: https://gist.github.com/6126370

@shashwatblack
Copy link

Edit in @minrk's code to support substring-matching and case insensitivity
https://gist.github.com/shashwatblack/54eb22b09d4cb9c67953f0146e590eb2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment