extra_hosts.py 943 B

123456789101112131415161718192021222324252627282930313233
  1. import ipaddress
  2. from typing import TYPE_CHECKING
  3. if TYPE_CHECKING:
  4. from render import Render
  5. try:
  6. from .error import RenderError
  7. except ImportError:
  8. from error import RenderError
  9. class ExtraHosts:
  10. def __init__(self, render_instance: "Render"):
  11. self._render_instance = render_instance
  12. self._extra_hosts: dict[str, str] = {}
  13. def add_host(self, host: str, ip: str):
  14. if not ip == "host-gateway":
  15. try:
  16. ipaddress.ip_address(ip)
  17. except ValueError:
  18. raise RenderError(f"Invalid IP address [{ip}] for host [{host}]")
  19. if host in self._extra_hosts:
  20. raise RenderError(f"Host [{host}] already added with [{self._extra_hosts[host]}]")
  21. self._extra_hosts[host] = ip
  22. def has_hosts(self):
  23. return len(self._extra_hosts) > 0
  24. def render(self):
  25. return {host: ip for host, ip in self._extra_hosts.items()}