experiment with mypy type annotations
[zonemaker.git] / zonemaker / zone.py
index 63195050780d58b1581adbf9a6dbdf9749b28c50..f5db2a8cfd9df7990823003ec65a1a3017362a6c 100644 (file)
@@ -1,12 +1,24 @@
+from typing import List, Dict, Any
+import ipaddress, re
+
 second = 1
 minute = 60*second
 hour = 60*minute
 day = 24*hour
 
+def hostname(name: str) -> str:
+    # check hostname for validity
+    label = r'[a-zA-Z90-9]([a-zA-Z90-9-]{0,61}[a-zA-Z90-9])?' # must not start or end with hyphen
+    pattern = r'^{0}(\.{0})*\.?'.format(label)
+    print(pattern)
+    if re.match(pattern, name):
+        return name
+    raise Exception(name+" is not a valid hostname")
+
 class Address:
     def __init__(self, IPv4 = None, IPv6 = None):
-        self._IPv4 = IPv4
-        self._IPv6 = IPv6
+        self._IPv4 = None if IPv4 is None else ipaddress.IPv4Address(IPv4)
+        self._IPv6 = None if IPv6 is None else ipaddress.IPv6Address(IPv6)
     
     def IPv4(self):
         return Address(IPv4 = self._IPv4)
@@ -32,11 +44,25 @@ class Delegation():
         pass
 
 class Zone:
-    def __init__(self, name, mail, NS,
-                 secondary_refresh, secondary_retry, secondary_discard,
-                 NX_TTL = None, A_TTL = None, other_TTL = None,
-                 domains = []):
+    def __init__(self, name: str, mail: str, NS: List[str],
+                 secondary_refresh: int, secondary_retry: int, secondary_discard: int,
+                 NX_TTL: int = None, A_TTL: int = None, other_TTL: int = None,
+                 domains: Dict[str, Any] = {}) -> None:
+        self._name = hostname(name)
+        if not mail.endswith('.'): raise Exception("Mail must be absolute, end with a dot")
+        atpos = mail.find('@')
+        if atpos < 0 or atpos > mail.find('.'): raise Exception("Mail must contain an @ before the first dot")
+        self._mail = hostname(mail.replace('@', '.', 1))
+        self._NS = list(map(hostname, NS))
+        
+        self._secondary_refresh = secondary_refresh
+        self._secondary_retry = secondary_retry
+        self._secondary_discard = secondary_discard
+        
         assert other_TTL is not None
         self._NX_TTL = other_TTL if NX_TTL is None else NX_TTL
         self._A_TTL = other_TTL if A_TTL is None else A_TTL
         self._other_TTL = other_TTL
+    
+    def write(self, file):
+        raise NotImplementedError()