Skip to content

Instantly share code, notes, and snippets.

@tonyseek
Last active March 25, 2019 16:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyseek/dd28d8fe6b1243d9eee9 to your computer and use it in GitHub Desktop.
Save tonyseek/dd28d8fe6b1243d9eee9 to your computer and use it in GitHub Desktop.
View your Git repository in the browser.
#!/usr/bin/env python
"""
The MIT License (MIT)
Copyright (c) 2019 Jiangge Zhang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import print_function, unicode_literals
import re
import sys
import subprocess
import collections
import webbrowser
import warnings
import argparse
try:
from urllib.parse import urlsplit, SplitResult
except ImportError:
from urlparse import urlsplit, SplitResult # noqa
GitRemote = collections.namedtuple('GitRemote', ['name', 'location', 'kind'])
def decode_bytes(text, encoding='utf-8'):
if isinstance(text, bytes):
return text.decode(encoding)
return text
def git_remote_list():
proc = subprocess.Popen(
args=['git', 'remote', '-v'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
stdout = decode_bytes(stdout)
stderr = decode_bytes(stderr)
if proc.returncode != 0:
raise RuntimeError(stderr, proc.returncode)
return [GitRemote(*line.split()) for line in stdout.strip().split('\n')]
def location_to_url(location):
result = re.match(r'(\w+)@([^:]+):(.+)', location)
if result:
ssh_user, ssh_host, ssh_path = result.groups()
if ssh_user != 'git':
warnings.warn(
'username of ssh location is "{0}", '
'expected "git"'.format(ssh_user))
if ssh_host in ('github.com', 'bitbucket.org'):
url_scheme = 'https'
else:
url_scheme = 'http'
url_host = ssh_host
url_path = remove_suffix(ssh_path, '.git')
return make_http_url(url_scheme, url_host, url_path)
result = urlsplit(location)
if result.scheme in ('http', 'https') and result.hostname:
url_path = remove_suffix(result.path, '.git')
return make_http_url(result.scheme, result.hostname, url_path)
raise RuntimeError('unknown remote url %r' % location)
def make_http_url(scheme, host, path, query=''):
split_result = SplitResult(
scheme=scheme,
netloc=host,
path=path,
query=query,
fragment='')
return split_result.geturl()
def remove_suffix(text, suffix):
if text.endswith(suffix):
return text[:-len(suffix)]
return text
def find_suitable_remote(remote_list, expected_name, expected_kind):
for remote in remote_list:
if remote.name == expected_name \
and remote.kind == '(%s)' % expected_kind:
return remote
raise RuntimeError('%s %s not found' % (expected_name, expected_kind))
def main():
parser = argparse.ArgumentParser()
try:
remote_list = git_remote_list()
remote_names = list({r.name for r in remote_list})
remote_kinds = list({r.kind.strip('()') for r in remote_list})
parser.add_argument(
'remote', nargs='?', default='origin', choices=remote_names,
help='the name of remote')
parser.add_argument(
'--type', dest='kind', default='fetch', choices=remote_kinds,
help='the type of remote')
parser.add_argument(
'--echo', dest='echo', action='store_true',
help='print the url instead of opening it')
parser.set_defaults(echo=False)
args = parser.parse_args()
remote = find_suitable_remote(remote_list, args.remote, args.kind)
url = location_to_url(remote.location)
if args.echo:
print(url)
else:
webbrowser.open_new_tab(url)
except RuntimeError as e:
print(e.args[0], file=sys.stderr)
return e.args[1] if len(e.args) > 2 else 1
else:
return 0
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment