git-url 1.5 KB

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