git-url 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. commit = oneliner('git', 'rev-parse', 'HEAD')
  9. local_branch = oneliner('git', 'branch', '--show-current')
  10. tag = None
  11. if local_branch.startswith('tags/'):
  12. tag = local_branch[5:]
  13. if tag.endswith('^0'):
  14. tag = tag[:-2]
  15. remote_url = oneliner('git', 'config', 'remote.origin.url')
  16. else:
  17. tracking_branch = oneliner('git', 'config', 'branch.%s.merge' % local_branch)
  18. if tracking_branch.startswith('refs/heads/'):
  19. tracking_branch = tracking_branch[len('refs/heads/'):]
  20. else:
  21. raise Exception("can't handle " + tracking_branch)
  22. tracking_remote = oneliner('git', 'config', 'branch.%s.remote' % local_branch)
  23. remote_url = oneliner('git', 'config', 'remote.%s.url' % tracking_remote)
  24. relpath = oneliner('git', 'rev-parse', '--show-prefix')[:-1]
  25. remote_url = re.sub(r'^(.+@.+):(.+)$', r'ssh://\1/\2', remote_url)
  26. if remote_url.endswith('.git'):
  27. remote_url = remote_url[:-len('.git')]
  28. parsed = urllib.parse.urlparse(remote_url)
  29. hostname = parsed.hostname
  30. if hostname.startswith('github.com-'):
  31. hostname = 'github.com'
  32. obj_type = 'tree'
  33. if len(sys.argv) == 2:
  34. obj_type = 'blob'
  35. repo_url = urllib.parse.urlunparse(('https', hostname, parsed.path, '', '', ''))
  36. def url_for(treeish):
  37. dir_url = '%s/%s/%s' % (repo_url, obj_type, treeish)
  38. if relpath:
  39. dir_url = '%s/%s' % (dir_url, relpath)
  40. if len(sys.argv) == 2:
  41. return '%s/%s' % (dir_url, sys.argv[1])
  42. else:
  43. return dir_url
  44. if tag is not None:
  45. print(url_for(tag))
  46. else:
  47. print(url_for(tracking_branch))
  48. print(url_for(commit))