git-url 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python3
  2. import re
  3. import subprocess
  4. import sys
  5. import urllib.parse
  6. def oneliner(*args):
  7. return subprocess.check_output(args, universal_newlines=True).strip()
  8. local_branch = oneliner('git', 'name-rev', '--name-only', 'HEAD')
  9. tracking_remote = oneliner('git', 'config', 'branch.%s.remote' % local_branch)
  10. tracking_branch = oneliner('git', 'config', 'branch.%s.merge' % local_branch)
  11. remote_url = oneliner('git', 'config', 'remote.%s.url' % tracking_remote)
  12. relpath = oneliner('git', 'rev-parse', '--show-prefix')[:-1]
  13. if tracking_branch.startswith('refs/heads/'):
  14. tracking_branch = tracking_branch[len('refs/heads/'):]
  15. else:
  16. raise Exception("can't handle " + tracking_branch)
  17. remote_url = re.sub(r'^(.+@.+):(.+)$', r'ssh://\1/\2', remote_url)
  18. if remote_url.endswith('.git'):
  19. remote_url = remote_url[:-len('.git')]
  20. parsed = urllib.parse.urlparse(remote_url)
  21. hostname = parsed.hostname
  22. if hostname == 'github.com-private':
  23. hostname = 'github.com'
  24. if hostname == 'github.com':
  25. repo_url = urllib.parse.urlunparse(('https', hostname, parsed.path, '', '', ''))
  26. dir_url = '%s/tree/%s' % (repo_url, tracking_branch)
  27. if relpath:
  28. dir_url = '%s/%s' % (dir_url, relpath)
  29. if len(sys.argv) == 2:
  30. print('%s/%s' % (dir_url, sys.argv[1]))
  31. else:
  32. print(dir_url)
  33. else:
  34. raise Exception("can't handle " + parsed.hostname)