git-url 1.4 KB

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