2 from dns.name import Name
3 from ipaddress import ip_address, IPv4Address, IPv6Address, ip_network, IPv4Network, IPv6Network
4 from datetime import timedelta
5 from typing import Any, List, Optional
8 IPAddress = IPv4Address | IPv6Address
9 IPNetwork = IPv4Network | IPv6Network
10 IPAddr = str | IPAddress | List[str | IPAddress]
13 def flatten_list(args: Any) -> List[Any]:
15 if isinstance(args, list) or isinstance(args, tuple):
26 def parse_address(addr: IPAddress | str) -> IPAddress:
27 if isinstance(addr, IPv4Address) or isinstance(addr, IPv6Address):
29 elif isinstance(addr, str):
30 return ip_address(addr)
32 raise ValueError('Cannot parse IP address')
35 def parse_network(addr: IPNetwork | str) -> IPNetwork:
36 if isinstance(addr, IPv4Network) or isinstance(addr, IPv6Network):
38 elif isinstance(addr, str):
39 return ip_network(addr)
41 raise ValueError('Cannot parse IP network')
44 def parse_name(name: str, relative: bool = False, origin: Optional[Name] = None) -> Name:
45 # FIXME: Names with escaped dots
46 if '.' in name and not relative and origin is None:
47 return dns.name.from_text(name)
49 return dns.name.from_text(name, origin=origin)
52 def parse_duration(delta: timedelta | int) -> int:
53 if isinstance(delta, timedelta):
54 return int(delta.total_seconds())
55 elif isinstance(delta, int):
58 raise ValueError('Cannot parse time duration')