| Total Complexity | 7 |
| Total Lines | 52 |
| Duplicated Lines | 0 % |
| Coverage | 100% |
| Changes | 0 | ||
| 1 | """ |
||
| 2 | syslog2irc.network |
||
| 3 | ~~~~~~~~~~~~~~~~~~ |
||
| 4 | |||
| 5 | :Copyright: 2007-2021 Jochen Kupperschmidt |
||
| 6 | :License: MIT, see LICENSE for details. |
||
| 7 | """ |
||
| 8 | |||
| 9 | 1 | from dataclasses import dataclass |
|
| 10 | 1 | from enum import Enum |
|
| 11 | |||
| 12 | |||
| 13 | 1 | TransportProtocol = Enum('TransportProtocol', ['TCP', 'UDP']) |
|
| 14 | |||
| 15 | |||
| 16 | 1 | @dataclass(frozen=True, order=True) |
|
| 17 | class Port: |
||
| 18 | """A network port.""" |
||
| 19 | |||
| 20 | 1 | number: int |
|
| 21 | 1 | transport_protocol: TransportProtocol |
|
| 22 | |||
| 23 | |||
| 24 | 1 | def format_port(port: Port) -> str: |
|
| 25 | """Return string representation for port.""" |
||
| 26 | 1 | return f'{port.number}/{port.transport_protocol.name.lower()}' |
|
| 27 | |||
| 28 | |||
| 29 | 1 | def parse_port(value: str) -> Port: |
|
| 30 | """Extract port number and protocol from string representation.""" |
||
| 31 | 1 | tokens = value.split('/', maxsplit=1) |
|
| 32 | 1 | if len(tokens) != 2: |
|
| 33 | 1 | raise ValueError(f'Invalid port string "{value}"') |
|
| 34 | |||
| 35 | 1 | number_str = tokens[0] |
|
| 36 | 1 | try: |
|
| 37 | 1 | number = int(number_str) |
|
| 38 | 1 | except ValueError: |
|
| 39 | 1 | raise ValueError(f'Invalid port number "{number_str}"') |
|
| 40 | 1 | if number < 1 or number > 65535: |
|
| 41 | 1 | raise ValueError(f'Invalid port number "{number_str}"') |
|
| 42 | |||
| 43 | 1 | transport_protocol_str = tokens[1] |
|
| 44 | 1 | try: |
|
| 45 | 1 | transport_protocol = TransportProtocol[transport_protocol_str.upper()] |
|
| 46 | 1 | except KeyError: |
|
| 47 | 1 | raise ValueError( |
|
| 48 | f'Unknown transport protocol "{transport_protocol_str}"' |
||
| 49 | ) |
||
| 50 | |||
| 51 | return Port(number=number, transport_protocol=transport_protocol) |
||
| 52 |