Passed
Push — main ( 287fd9...ba5fce )
by Jochen
30:44
created

weitersager.config._get_log_level()   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
cc 2
eloc 5
nop 1
dl 0
loc 7
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
c 0
b 0
f 0
1
"""
2
weitersager.config
3
~~~~~~~~~~~~~~~~~~
4
5
Configuration loading
6
7
:Copyright: 2007-2021 Jochen Kupperschmidt
8
:License: MIT, see LICENSE for details.
9
"""
10
11 1
from __future__ import annotations
12 1
from dataclasses import dataclass
13 1
import logging
14 1
from pathlib import Path
15 1
from typing import Any, Dict, Iterator, Optional, Set
16
17 1
import rtoml
18
19
20 1
DEFAULT_HTTP_HOST = '127.0.0.1'
21 1
DEFAULT_HTTP_PORT = 8080
22 1
DEFAULT_IRC_SERVER_PORT = 6667
23 1
DEFAULT_IRC_REALNAME = 'Weitersager'
24
25
26 1
class ConfigurationError(Exception):
27
    """Indicates a configuration error."""
28
29
30 1
@dataclass(frozen=True)
31
class Config:
32 1
    log_level: str
33 1
    http: HttpConfig
34 1
    irc: IrcConfig
35
36
37 1
@dataclass(frozen=True)
38
class HttpConfig:
39
    """An HTTP receiver configuration."""
40
41 1
    host: str
42 1
    port: int
43 1
    api_tokens: Set[str]
44
45
46 1
@dataclass(frozen=True)
47
class IrcServer:
48
    """An IRC server."""
49
50 1
    host: str
51 1
    port: int
52 1
    ssl: bool = False
53 1
    password: Optional[str] = None
54 1
    rate_limit: Optional[float] = None
55
56
57 1
@dataclass(frozen=True, order=True)
58
class IrcChannel:
59
    """An IRC channel."""
60
61 1
    name: str
62 1
    password: Optional[str] = None
63
64
65 1
@dataclass(frozen=True)
66
class IrcConfig:
67
    """An IRC bot configuration."""
68
69 1
    server: Optional[IrcServer]
70 1
    nickname: str
71 1
    realname: str
72 1
    channels: Set[IrcChannel]
73
74
75 1
def load_config(path: Path) -> Config:
76
    """Load configuration from file."""
77 1
    data = rtoml.load(path)
78
79 1
    log_level = _get_log_level(data)
80 1
    http_config = _get_http_config(data)
81 1
    irc_config = _get_irc_config(data)
82
83 1
    return Config(
84
        log_level=log_level,
85
        http=http_config,
86
        irc=irc_config,
87
    )
88
89
90 1
def _get_log_level(data: Dict[str, Any]) -> str:
91 1
    level = data.get('log_level', 'debug').upper()
92
93 1
    if level not in {'CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'}:
94
        raise ConfigurationError(f'Unknown log level "{level}"')
95
96 1
    return level
97
98
99 1
def _get_http_config(data: Dict[str, Any]) -> HttpConfig:
100 1
    data_http = data.get('http', {})
101
102 1
    host = data_http.get('host', DEFAULT_HTTP_HOST)
103 1
    port = int(data_http.get('port', DEFAULT_HTTP_PORT))
104 1
    api_tokens = set(data_http.get('api_tokens', []))
105
106 1
    return HttpConfig(host, port, api_tokens)
107
108
109 1
def _get_irc_config(data: Dict[str, Any]) -> IrcConfig:
110 1
    data_irc = data['irc']
111
112 1
    server = _get_irc_server(data_irc)
113 1
    nickname = data_irc['bot']['nickname']
114 1
    realname = data_irc['bot'].get('realname', DEFAULT_IRC_REALNAME)
115 1
    channels = set(_get_irc_channels(data_irc))
116
117 1
    return IrcConfig(
118
        server=server,
119
        nickname=nickname,
120
        realname=realname,
121
        channels=channels,
122
    )
123
124
125 1
def _get_irc_server(data_irc: Any) -> Optional[IrcServer]:
126 1
    data_server = data_irc.get('server')
127 1
    if data_server is None:
128 1
        return None
129
130 1
    host = data_server.get('host')
131 1
    if not host:
132 1
        return None
133
134 1
    port = int(data_server.get('port', DEFAULT_IRC_SERVER_PORT))
135 1
    ssl = data_server.get('ssl', False)
136 1
    password = data_server.get('password')
137 1
    rate_limit_str = data_server.get('rate_limit')
138 1
    rate_limit = float(rate_limit_str) if rate_limit_str else None
139
140 1
    return IrcServer(
141
        host=host, port=port, ssl=ssl, password=password, rate_limit=rate_limit
142
    )
143
144
145 1
def _get_irc_channels(data_irc: Any) -> Iterator[IrcChannel]:
146 1
    for channel in data_irc.get('channels', []):
147 1
        name = channel['name']
148 1
        password = channel.get('password')
149
        yield IrcChannel(name, password)
150