Skip to content

Instantly share code, notes, and snippets.

@sergray
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergray/d2a68d395cb7c3342463 to your computer and use it in GitHub Desktop.
Save sergray/d2a68d395cb7c3342463 to your computer and use it in GitHub Desktop.
Python command gico checking out the latest version of git branch by name substring
#!/usr/bin/env python
"""Checkout the latest version of git branch by name substring"""
from __future__ import print_function
import sys
from subprocess import check_output
def sanitize(output):
normalize = lambda br: br.strip(' *')
return [normalize(br) for br in output.decode('utf-8').split() if normalize(br)]
def ensure_single(matches):
if len(matches) > 1:
print('Multiple matches:', ' '.join(matches))
sys.exit(1)
else:
return matches[0].rsplit('/')[-1]
def main(name):
check_output(['git', 'fetch', 'origin'])
remote_branches = sanitize(check_output(['git', 'branch', '-r']))
local_branches = sanitize(check_output(['git', 'branch']))
by_name = lambda branch: name in branch
remote_matches = filter(by_name, remote_branches)
local_matches = filter(by_name, local_branches)
if remote_matches:
name = ensure_single(remote_matches)
check_output(['git', 'checkout', name])
check_output(['git', 'pull', '--ff-only'])
elif local_matches:
name = ensure_single(local_matches)
check_output(['git', 'checkout', name])
else:
print('no matching branches found')
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment