names.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from __future__ import annotations
  2. class InvalidRepositoryError(Exception):
  3. """The given string is not a valid repository name."""
  4. def resolve_repository_name(repo_name: str) -> tuple[str, str]:
  5. if "://" in repo_name:
  6. raise InvalidRepositoryError(
  7. f"Repository name cannot contain a scheme ({repo_name})"
  8. )
  9. index_name, remote_name = split_repo_name(repo_name)
  10. if index_name[0] == "-" or index_name[-1] == "-":
  11. raise InvalidRepositoryError(
  12. f"Invalid index name ({index_name}). Cannot begin or end with a hyphen."
  13. )
  14. return resolve_index_name(index_name), remote_name
  15. def resolve_index_name(index_name: str) -> str:
  16. index_name = convert_to_hostname(index_name)
  17. if index_name == "index.docker.io":
  18. index_name = "docker.io"
  19. return index_name
  20. def split_repo_name(repo_name: str) -> tuple[str, str]:
  21. parts = repo_name.split("/", 1)
  22. if len(parts) == 1 or (
  23. "." not in parts[0] and ":" not in parts[0] and parts[0] != "localhost"
  24. ):
  25. # This is a docker index repo (ex: username/foobar or ubuntu)
  26. return "docker.io", repo_name
  27. return parts[0], parts[1]
  28. def convert_to_hostname(url: str) -> str:
  29. return url.replace("http://", "").replace("https://", "").split("/", 1)[0]