~nova/fletcher

fletcher/load_config.py -rw-r--r-- 12.7 KiB
ece10afa — Novalinium f-string issue 9 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import os
import discord
import copy
import configparser
import logging

logger = logging.getLogger("fletcher")


class FletcherConfig:
    config_dict = None

    def __init__(self, base_config_path=os.getenv("FLETCHER_CONFIG", "./.fletcherrc")):
        config = configparser.ConfigParser()
        config.optionxform = str
        config.read(base_config_path)
        config = {
            s: {k: self.normalize(v, key=k) for k, v in dict(config.items(s)).items()}
            for s in config.sections()
        }
        self.config_dict = config

        if os.path.isdir(config.get("extra", {}).get("rc-path", "/unavailable")):
            for file_name in os.listdir(config.get("extra", {}).get("rc-path")):
                if file_name.isdigit():
                    guild_config = configparser.ConfigParser()
                    guild_config.optionxform = str
                    guild_config.read(f'{config["extra"]["rc-path"]}/{file_name}')
                    for section_name, section in guild_config.items():
                        if section_name.lower() in ["default", "general"]:
                            section_key = f"Guild {file_name}"
                        else:
                            section_key = f"Guild {file_name} - {section_name}"
                        logger.debug(f"RM: Adding section for {section_key}")
                        if section_key in config:
                            logger.info(
                                f"FC: Duplicate section definition for {section_key}, duplicate keys may be overwritten"
                            )
                        else:
                            config[section_key] = {}
                        for k, v in guild_config.items(section_name):
                            if k.startswith("SECTION_"):
                                k = k.split("_", 2)[1:]
                                subsection_key = k[0]
                                k = k[1]
                                if subsection_key not in config[section_key]:
                                    config[section_key][subsection_key] = {}
                                config[section_key][subsection_key][k] = self.normalize(
                                    v, key=k
                                )
                            else:
                                config[section_key][k] = self.normalize(v, key=k)
        self.config_dict = config
        self.defaults = {
            "database": {
                "engine": "postgres",
                "user": "fletcher_user",
                "tablespace": "fletcher",
                "host": "localhost",
            },
            "discord": {
                "botNavel": "ƒ",
                "botLogName": "fletcher",
                "globalAdminIsServerAdmin": True,
                "profile": False,
            },
            "nickmask": {"conflictbots": [431544605209788416],},
        }
        self.guild_defaults = {
            "synchronize": False,
            "sync-deletions": True,
            "sync-edits": True,
            "blacklist-commands": [],
            "color-role-autocreate": True,
        }
        self.channel_defaults = {"synchronize": False}

    def clone(self):
        return copy.deepcopy(self)

    def normalize_booleans(self, value, strict=False):
        if type(value) is bool:
            return value
        elif str(value).lower().strip() in ["on", "true", "yes"]:
            return True
        elif str(value).lower().strip() in ["off", "false", "no"]:
            return False
        elif strict:
            return None
        else:
            return value

    def normalize_numbers(self, value, strict=False):
        if type(value) in [int, float]:
            return value
        elif str(value).isdigit():
            return int(value)
        elif str(value).isnumeric():
            return float(value)
        elif strict:
            return None
        else:
            return value

    def str_to_array(self, string, delim=",", strip=True, filter_function=None.__ne__):
        array = string.split(delim)
        if strip:
            array = map(str.strip, array)
        if all(str(el).isnumeric() for el in array):
            array = map(int, array)
        return list(filter(filter_function, array))

    def normalize_array(self, value, strict=False):
        if type(value) is list:
            return value
        elif ", " in value or value.startswith(" ") or value.endswith(" "):
            return self.str_to_array(value, strip=True) or []
        elif "," in value:
            return self.str_to_array(value, strip=False) or []
        elif strict:
            return None
        else:
            return [value]

    def normalize(self, value, key=""):
        if type(value) is dict:
            return {k: self.normalize(v) for k, v in value.items()}
        elif type(value) is list:
            return [self.normalize(v) for v in value]
        elif "list" in key:
            return [self.normalize(v) for v in self.normalize_array(value)]
        else:
            return self.normalize_numbers(
                self.normalize_booleans(value, strict=False), strict=False
            )

    def __getitem__(self, key):
        return self.get(key=key)

    def get(
        self,
        key=None,
        default=None,
        section=None,
        guild=None,
        channel=None,
        use_category_as_channel_fallback=True,
        use_guild_as_channel_fallback=True,
    ):
        if guild is None and channel:
            if type(channel) in [
                discord.TextChannel,
                discord.VoiceChannel,
                discord.CategoryChannel,
            ]:
                guild = channel.guild
            else:
                guild = 0
        if hasattr(guild, "id"):
            guild = guild.id
        if hasattr(channel, "id"):
            channel = channel.id
        if (
            guild
            and channel
            and self.client.get_guild(guild).get_channel(channel).category_id
        ):
            category = self.client.get_guild(guild).get_channel(channel).category_id
        else:
            category = None
        value = None
        if key is None and section is None and guild is None and channel is None:
            value = self.config_dict or self.defaults
        elif key is not None and section is None and guild is None and channel is None:
            value = self.config_dict.get(key, self.defaults.get(key))
        elif key is None and section is not None and guild is None and channel is None:
            value = self.config_dict.get(section, self.defaults.get(section, {}))
        elif (
            key is not None
            and section is not None
            and guild is None
            and channel is None
        ):
            value = self.config_dict.get(section, {}).get(key, None)
            if value is None:
                value = self.defaults.get(section, {}).get(key, None)
        elif key is None and section is None and guild is not None and channel is None:
            value = self.config_dict.get(f"Guild {guild:d}", self.guild_defaults)
        elif (
            key is not None
            and section is None
            and guild is not None
            and channel is None
        ):
            value = self.config_dict.get(f"Guild {guild:d}", {}).get(key, None)
            if value is None:
                value = self.guild_defaults.get(key, None)
        elif (
            key is None
            and section is not None
            and guild is not None
            and channel is None
        ):
            value = self.config_dict.get(f"Guild {guild:d}", {}).get(section, None)
            if value is None:
                value = self.guild_defaults.get(section, {})
        elif (
            key is not None
            and section is not None
            and guild is not None
            and channel is None
        ):
            value = (
                self.config_dict.get(f"Guild {guild:d}", {})
                .get(section, {})
                .get(key, None)
            )
            if value is None:
                value = self.guild_defaults.get(section, {}).get(key, None)
        elif key is None and section is None and guild is None and channel is not None:
            raise ValueError(
                "Guild was not specified and cannot be inferred from channel [This code should be unreachable, something has gone terribly wrong]"
            )
        elif (
            key is not None
            and section is None
            and guild is None
            and channel is not None
        ):
            raise ValueError(
                "Guild was not specified and cannot be inferred from channel [This code should be unreachable, something has gone terribly wrong]"
            )
        elif (
            key is None
            and section is not None
            and guild is None
            and channel is not None
        ):
            raise ValueError(
                "Guild was not specified and cannot be inferred from channel [This code should be unreachable, something has gone terribly wrong]"
            )
        elif (
            key is not None
            and section is not None
            and guild is None
            and channel is not None
        ):
            raise ValueError(
                "Guild was not specified and cannot be inferred from channel [This code should be unreachable, something has gone terribly wrong]"
            )
        elif (
            key is not None
            and section is None
            and guild is not None
            and channel is not None
        ):
            value = self.config_dict.get(f"Guild {guild:d} - {channel:d}", {}).get(
                key, None
            )
            if not value and use_category_as_channel_fallback:
                value = self.config_dict.get(f"Guild {guild:d} - {category:d}", {}).get(
                    key, None
                )
            if not value and use_guild_as_channel_fallback:
                value = self.config_dict.get(f"Guild {guild:d}", {}).get(key, None)
            if not value:
                value = self.channel_defaults.get(key, None)
            if not value and use_guild_as_channel_fallback:
                value = self.guild_defaults.get(key, None)
        elif (
            key is None
            and section is not None
            and guild is not None
            and channel is not None
        ):
            value = self.config_dict.get(f"Guild {guild:d} - {channel:d}", {}).get(
                section, None
            )
            if not value and use_category_as_channel_fallback:
                value = self.config_dict.get(f"Guild {guild:d} - {category:d}").get(
                    section, None
                )
            if not value and use_guild_as_channel_fallback:
                value = self.config_dict.get(f"Guild {guild:d}", {}).get(section, None)
            if not value:
                value = self.channel_defaults.get(section, None)
            if not value and use_guild_as_channel_fallback:
                value = self.guild_defaults.get(section, None)
            if not value:
                value = {}
        elif (
            key is not None
            and section is not None
            and guild is not None
            and channel is not None
        ):
            value = (
                self.config_dict.get(f"Guild {guild:d} - {channel:d}", {})
                .get(section, {})
                .get(key, None)
            )
            if not value and use_category_as_channel_fallback:
                value = (
                    self.config_dict.get(f"Guild {guild:d} - {category:d}")
                    .get(section, {})
                    .get(key, None)
                )
            if not value and use_guild_as_channel_fallback:
                value = (
                    self.config_dict.get(f"Guild {guild:d}", {})
                    .get(section, {})
                    .get(key, None)
                )
            if not value:
                value = self.channel_defaults.get(section, {}).get(key, None)
            if not value and use_guild_as_channel_fallback:
                value = self.guild_defaults.get(section, {}).get(key, None)
        if value is None or value == {} and default:
            value = default
        return value

    def __contains__(self, key):
        if type(key) in [discord.Guild]:
            return f"Guild {guild.id:d}" in self.config_dict
        elif type(key) in [
            discord.TextChannel,
            discord.VoiceChannel,
            discord.CategoryChannel,
        ]:
            return f"Guild {key.guild.id:d} - {key.id:d}" in self.config_dict
        elif type(key) in [discord.DMChannel]:
            return f"Guild 0 - {key.recipient.id:d}" in self.config_dict
        else:
            return key in self.config_dict or key in self.defaults