git-url 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env python3
  2. from __future__ import annotations
  3. import re
  4. import subprocess
  5. import sys
  6. import typing
  7. import urllib.parse
  8. if typing.TYPE_CHECKING:
  9. from _typeshed import StrOrBytesPath
  10. def oneliner(*args) -> str:
  11. return subprocess.run(args, check=True, capture_output=True, text=True).stdout.strip()
  12. commit = oneliner('git', 'rev-parse', 'HEAD')
  13. local_branch = oneliner('git', 'branch', '--show-current')
  14. tag = None
  15. if local_branch.startswith('tags/'):
  16. tag = local_branch[5:]
  17. if tag.endswith('^0'):
  18. tag = tag[:-2]
  19. remote_url = oneliner('git', 'config', 'remote.origin.url')
  20. else:
  21. tracking_branch = oneliner('git', 'config', 'branch.%s.merge' % local_branch)
  22. if tracking_branch.startswith('refs/heads/'):
  23. tracking_branch = tracking_branch[len('refs/heads/'):]
  24. else:
  25. raise Exception("can't handle " + tracking_branch)
  26. tracking_remote = oneliner('git', 'config', 'branch.%s.remote' % local_branch)
  27. remote_url = oneliner('git', 'config', 'remote.%s.url' % tracking_remote)
  28. relpath = oneliner('git', 'rev-parse', '--show-prefix')[:-1]
  29. remote_url = re.sub(r'^(.+@.+):(.+)$', r'ssh://\1/\2', remote_url)
  30. if remote_url.endswith('.git'):
  31. remote_url = remote_url[:-len('.git')]
  32. parsed = urllib.parse.urlparse(remote_url)
  33. hostname = parsed.hostname
  34. if hostname.startswith('github.com-'):
  35. hostname = 'github.com'
  36. obj_type = 'tree'
  37. if len(sys.argv) == 2:
  38. obj_type = 'blob'
  39. repo_url = urllib.parse.urlunparse(('https', hostname, parsed.path, '', '', ''))
  40. def url_for(treeish: str) -> str:
  41. dir_url = '%s/%s/%s' % (repo_url, obj_type, treeish)
  42. if relpath:
  43. dir_url = '%s/%s' % (dir_url, relpath)
  44. if len(sys.argv) == 2:
  45. return '%s/%s' % (dir_url, sys.argv[1])
  46. else:
  47. return dir_url
  48. if tag is not None:
  49. print(url_for(tag))
  50. else:
  51. print(url_for(tracking_branch))
  52. print(url_for(commit))