Debian Codegraph @

lib/parse/config.py

raw
1 # -*- coding: utf-8 -*-
2 # This program is free software; you can redistribute it and/or modify
3 # it under the terms of the GNU General Public License as published by
4 # the Free Software Foundation; either version 2 of the License, or
5 # (at your option) any later version.
6 #
7 # This program is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 # GNU General Public License for more details.
11 #
12 # You should have received a copy of the GNU General Public License
13 # along with this program; if not, write to the Free Software
14 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
15 # MA 02110-1301, USA.
16 #
17 # Author: Mauro Soria
18
19 from __future__ import annotations
20
21 import configparser
22 import json
23
24
25 class ConfigParser(configparser.ConfigParser):
26 def safe_get(
27 self,
28 section: str,
29 option: str,
30 default: str | None = None,
31 allowed: tuple[str, ...] | None = None,
32 ) -> str | None:
33 try:
34 value = super().get(section, option)
35
36 if allowed and value not in allowed:
37 return default
38
39 return value
40 except (configparser.NoSectionError, configparser.NoOptionError):
41 return default
42
43 def safe_getfloat(
44 self,
45 section: str,
46 option: str,
47 default: float = 0.0,
48 allowed: tuple[float, ...] | None = None,
49 ) -> float:
50 try:
51 value = super().getfloat(section, option)
52
53 if allowed and value not in allowed:
54 return default
55
56 return value
57 except (configparser.NoSectionError, configparser.NoOptionError):
58 return default
59
60 def safe_getboolean(
61 self,
62 section: str,
63 option: str,
64 default: bool = False,
65 allowed: tuple[bool, ...] | None = None,
66 ) -> bool:
67 try:
68 value = super().getboolean(section, option)
69
70 if allowed and value not in allowed:
71 return default
72
73 return value
74 except (configparser.NoSectionError, configparser.NoOptionError):
75 return default
76
77 def safe_getint(
78 self,
79 section: str,
80 option: str,
81 default: int = 0,
82 allowed: tuple[int, ...] | None = None,
83 ) -> int:
84 try:
85 value = super().getint(section, option)
86
87 if allowed and value not in allowed:
88 return default
89
90 return value
91 except (configparser.NoSectionError, configparser.NoOptionError):
92 return default
93
94 def safe_getlist(
95 self,
96 section: str,
97 option: str,
98 default: list[str] = [],
99 allowed: tuple[str, ...] | None = None,
100 ) -> list[str]:
101 try:
102 try:
103 value = json.loads(super().get(section, option))
104 except json.decoder.JSONDecodeError:
105 value = [super().get(section, option)]
106
107 if allowed and set(value) - set(allowed):
108 return default
109
110 return value
111 except (configparser.NoSectionError, configparser.NoOptionError):
112 return default