Skip to content

Commit 38f211d

Browse files
Fix a bunch of shit
1 parent 7fe94f0 commit 38f211d

13 files changed

Lines changed: 303 additions & 75 deletions

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,7 @@ Where an old variable is not listed, [the example configuration file](tex-bot-de
268268
| `DISCORD_BOT_TOKEN` | `discord:bot-token` |
269269
| `DISCORD_GUILD_ID` | `discord:main-guild-id` |
270270
| `DISCORD_LOG_CHANNEL_WEBHOOK_URL` | `logging:discord-channel:webhook-url` |
271+
| `DISCORD_LOG_LEVEL` | `logging:discord-channel:log-level` |
271272
| `CONSOLE_LOG_LEVEL` | `logging:console:log-level` |
272273
| `GROUP_NAME` | `community-group:full-name` |
273274
| `GROUP_SHORT_NAME` | `community-group:short-name` |
@@ -278,6 +279,8 @@ Where an old variable is not listed, [the example configuration file](tex-bot-de
278279
| `MEMBERSHIP_DEPENDENT_ROLES` | `community-group:membership-dependent-roles` |
279280
| `ORGANISATION_ID` | `community-group:msl:organisation-id` |
280281
| `SU_PLATFORM_ACCESS_COOKIE` | `community-group:msl:auth-cookie` |
282+
| `AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING` | `community-group:msl:auto-cookie-checking:enabled` |
283+
| `AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL` | `community-group:msl:auto-cookie-checking:interval` |
281284
| `PING_COMMAND_EASTER_EGG_PROBABILITY` | `commands:ping:easter-egg-probability` |
282285
| `STATISTICS_DAYS` | `commands:stats:lookback-days` |
283286
| `STATISTICS_ROLES` | `commands:stats:displayed-roles` |
@@ -288,6 +291,7 @@ Where an old variable is not listed, [the example configuration file](tex-bot-de
288291
| `SEND_GET_ROLES_REMINDERS` | `reminders:send-get-roles-reminders:enabled` |
289292
| `SEND_GET_ROLES_REMINDERS_DELAY` | `reminders:send-get-roles-reminders:delay` |
290293
| `ADVANCED_SEND_GET_ROLES_REMINDERS_INTERVAL` | `reminders:send-get-roles-reminders:interval` |
294+
| `AUTO_ADD_COMMITTEE_TO_THREADS` | `auto-add-committee-to-threads` |
291295

292296
Two differences are worth noting while migrating:
293297

‎cogs/induct.py‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,14 +109,27 @@ async def on_member_update(self, before: discord.Member, after: discord.Member)
109109
]
110110

111111
if user_type != "member":
112+
# NOTE: Both links are optional, so the sentence pointing at each one is left
113+
# out entirely rather than sent holding a link that goes nowhere.
114+
PURCHASE_MEMBERSHIP_MESSAGE: Final[str] = (
115+
f"Just head to {settings.community_group.links.purchase_membership}. "
116+
if settings.community_group.links.purchase_membership is not None
117+
else ""
118+
)
119+
MEMBERSHIP_PERKS_MESSAGE: Final[str] = (
120+
f" Checkout all the perks at {settings.community_group.links.membership_perks}"
121+
if settings.community_group.links.membership_perks is not None
122+
else ""
123+
)
124+
112125
messages_to_send.append(
113126
f"You can also get yourself an annual membership "
114127
f"to {self.bot.group_full_name} for only £5! "
115-
f"Just head to {settings.community_group.links.purchase_membership}. "
128+
f"{PURCHASE_MEMBERSHIP_MESSAGE}"
116129
"You'll get awesome perks like a free T-shirt:shirt:, "
117130
"access to member only events:calendar_spiral: and a cool green name on "
118-
f"the {self.bot.group_short_name} Discord server:green_square:! "
119-
f"Checkout all the perks at {settings.community_group.links.membership_perks}"
131+
f"the {self.bot.group_short_name} Discord server:green_square:!"
132+
f"{MEMBERSHIP_PERKS_MESSAGE}"
120133
)
121134

122135
try:

‎config/__init__.py‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
from collections.abc import Mapping, Sequence
4141
from collections.abc import Set as AbstractSet
4242
from logging import Logger
43+
from pathlib import Path
4344
from typing import Final
4445

4546

@@ -83,17 +84,22 @@ class ConfigReloadResult(NamedTuple):
8384
restart_required_settings: "AbstractSet[str]"
8485

8586

86-
def reload_settings() -> ConfigReloadResult:
87+
def reload_settings(file_path: "Path | None" = None) -> ConfigReloadResult:
8788
"""
8889
Reload the deployment configuration file, applying any settings that have changed.
8990
9091
Returns the settings key paths whose values have changed, along with the subset of
9192
those that cannot take effect until TeX-Bot is restarted.
9293
94+
The configuration file is located afresh unless one is given explicitly. A change
95+
written by `set_setting()` or `unset_setting()` names the file it was written into,
96+
so that the change is always read back out of the file it was made to, rather than
97+
out of whichever file would be located now.
98+
9399
The currently loaded configuration is left untouched if the file cannot be read or
94100
contains invalid settings.
95101
"""
96-
CHANGED_SETTINGS: Final[AbstractSet[str]] = settings.reload()
102+
CHANGED_SETTINGS: Final[AbstractSet[str]] = settings.reload(file_path)
97103

98104
if any(changed_setting.startswith("logging:") for changed_setting in CHANGED_SETTINGS):
99105
apply_logging_settings(settings.logging)
@@ -137,7 +143,7 @@ def set_setting(setting_name: str, raw_value: str) -> ConfigReloadResult:
137143

138144
UPDATED_DOCUMENT.write()
139145

140-
return reload_settings()
146+
return reload_settings(UPDATED_DOCUMENT.file_path)
141147

142148

143149
def unset_setting(setting_name: str) -> ConfigReloadResult | None:
@@ -160,7 +166,7 @@ def unset_setting(setting_name: str) -> ConfigReloadResult | None:
160166

161167
UPDATED_DOCUMENT.write()
162168

163-
return reload_settings()
169+
return reload_settings(UPDATED_DOCUMENT.file_path)
164170

165171

166172
def run_setup() -> None:

‎config/_document.py‎

Lines changed: 43 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -339,48 +339,65 @@ def line_number_of(self, key_path: "Sequence[str | int]") -> int | None:
339339

340340
key: str | int
341341
for key in key_path:
342-
line_comments: object = getattr(node, "lc", None)
343-
NODE_CONTAINS_KEY: bool = bool(
344-
line_comments is not None
345-
and isinstance(node, (dict, list))
346-
and (key in node if isinstance(node, dict) else False)
347-
)
348-
if not NODE_CONTAINS_KEY:
349-
break
350-
351-
if TYPE_CHECKING:
352-
assert isinstance(node, dict)
353-
354-
LINE_NUMBER_OF_KEY: int | None = self._line_number_of_key(node, key)
355-
if LINE_NUMBER_OF_KEY is None:
342+
RESOLVED_KEY: tuple[int, object] | None = self._resolved_key(node, key)
343+
if RESOLVED_KEY is None:
356344
break
357345

358-
deepest_known_line_number = LINE_NUMBER_OF_KEY
359-
node = node[key]
346+
deepest_known_line_number, node = RESOLVED_KEY
360347

361348
return deepest_known_line_number
362349

363350
@staticmethod
364-
def _line_number_of_key(node: "dict[object, object]", key: "str | int") -> int | None:
351+
def _resolved_key(node: object, key: "str | int") -> "tuple[int, object] | None":
365352
"""
366-
Return the line that the given key of the given mapping was parsed from.
353+
Resolve one key of a key path, returning its line paired with the value held at it.
354+
355+
Both mappings & sequences are resolved, because a validation failure reported
356+
against a single entry of a sequence (one role within `displayed-roles`, for
357+
example) names that entry by its index, & so should be pointed at the line
358+
holding it rather than at the line the sequence itself begins upon.
367359
368-
`None` is returned for a key that was added to the document rather than parsed
369-
from the file, because such a key has no line within the file to report. This
370-
happens whenever the `/config` command writes a setting for the first time.
360+
`None` is returned where the node does not hold the given key at all, and also
361+
for a key that was added to the document rather than parsed from the file,
362+
because such a key has no line within the file to report. The latter happens
363+
whenever the `/config` command writes a setting for the first time.
371364
"""
365+
# NOTE: A node parsed by the round-trip parser carries the `lc` line-comment data
366+
# that the positions below are read from; one added to the document does not.
367+
if getattr(node, "lc", None) is None:
368+
return None
369+
372370
key_position: object
373-
try:
374-
key_position = node.lc.key(key) # type: ignore[attr-defined]
375-
except KeyError:
371+
child_node: object
372+
373+
if isinstance(node, dict):
374+
if key not in node:
375+
return None
376+
377+
try:
378+
key_position = node.lc.key(key) # type: ignore[attr-defined]
379+
except KeyError:
380+
return None
381+
382+
child_node = node[key]
383+
384+
elif isinstance(node, list) and isinstance(key, int) and 0 <= key < len(node):
385+
try:
386+
key_position = node.lc.item(key) # type: ignore[attr-defined]
387+
except (KeyError, IndexError):
388+
return None
389+
390+
child_node = node[key]
391+
392+
else:
376393
return None
377394

378395
if not isinstance(key_position, tuple):
379396
return None
380397

381-
# NOTE: `lc.key()` reports a zero-indexed line, whereas humans (& every editor)
398+
# NOTE: `lc` reports a zero-indexed line, whereas humans (& every editor)
382399
# count the first line of a file as line 1.
383-
return int(key_position[0]) + 1
400+
return (int(key_position[0]) + 1, child_node)
384401

385402
def _format_single_error(self, key_path: "Sequence[str | int]", message: str) -> str:
386403
"""Format a single validation failure, prefixed with the location that caused it."""

‎config/_editor.py‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@
5858

5959
UNSET_VALUE_DISPLAY: "Final[str]" = "_(not set)_"
6060

61-
# NOTE: Anything YAML would read back as a value other than a string, so that a value
62-
# given as one of these words is not written into the file as bare text.
61+
# NOTE: The ways of writing "nothing" that YAML recognises, so that a setting cleared by
62+
# one of them is cleared rather than being set to the word itself.
6363
_NULL_LITERALS: "Final[frozenset[str]]" = frozenset({"null", "~"})
6464

6565

@@ -99,9 +99,19 @@ def parse_setting_value(setting_name: str, raw_value: str) -> object:
9999
like a number (an organisation ID of `1234`, for example) is not written as one &
100100
then rejected for being the wrong type. Quoting such a value is still respected,
101101
so that `"1234"` means the same as `1234` rather than including the quotes.
102+
103+
Writing `null` (or `~`) clears a setting whatever type it holds, including one that
104+
holds text. `/config unset` removes such a setting from the file altogether, whereas
105+
this leaves it written there, holding nothing.
102106
"""
103107
PARSED_VALUE: Final[object] = _read_as_yaml(raw_value)
104108

109+
if raw_value.strip().lower() in _NULL_LITERALS:
110+
# NOTE: Clearing a setting is meant the same way whatever type that setting holds,
111+
# so one declared to hold text is no exception: keeping `null` as the text it
112+
# looks like would set that setting to the word itself rather than to nothing.
113+
return None
114+
105115
if setting_metadata(setting_name).holds_text:
106116
return PARSED_VALUE if isinstance(PARSED_VALUE, str) else raw_value
107117

@@ -110,7 +120,7 @@ def parse_setting_value(setting_name: str, raw_value: str) -> object:
110120
# `Computer Science: Society` into a single setting meant it as plain text.
111121
return raw_value
112122

113-
if PARSED_VALUE is None and raw_value.strip().lower() not in _NULL_LITERALS:
123+
if PARSED_VALUE is None:
114124
# NOTE: A value beginning with `#` parses as a comment, & so as nothing at all,
115125
# as does a value that cannot be read as YAML at all.
116126
return raw_value

‎config/_logging.py‎

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,11 @@
1616
from logging import Handler, Logger
1717
from typing import Final
1818

19-
from ._schema import LoggingSettings
19+
from ._schema import (
20+
DiscordAPILoggingSettings,
21+
DiscordChannelLoggingSettings,
22+
LoggingSettings,
23+
)
2024

2125

2226
__all__: "Sequence[str]" = ("DISCORD_LOGGER_NAME", "LOGGER_NAME", "apply_logging_settings")
@@ -36,11 +40,23 @@
3640
discord_logger: "Final[Logger]" = logging.getLogger(DISCORD_LOGGER_NAME)
3741

3842

39-
def _remove_handlers_of_type(target_logger: "Logger", handler_type: type) -> None:
40-
"""Remove every handler of the given type from the given logger."""
43+
def _remove_handlers_of_type(
44+
target_logger: "Logger", handler_type: type, *, excluding: type | None = None
45+
) -> None:
46+
"""
47+
Remove every handler of the given type from the given logger.
48+
49+
A subtype of that type may be excluded, because the logging module's own handler
50+
hierarchy does not match the destinations they write to: `FileHandler` subclasses
51+
`StreamHandler`, so removing every stream handler would otherwise also remove the
52+
file handler that a different destination's settings are responsible for.
53+
"""
4154
existing_handler: Handler
4255
for existing_handler in tuple(target_logger.handlers):
43-
if isinstance(existing_handler, handler_type):
56+
HANDLER_IS_EXCLUDED: bool = excluding is not None and isinstance(
57+
existing_handler, excluding
58+
)
59+
if isinstance(existing_handler, handler_type) and not HANDLER_IS_EXCLUDED:
4460
target_logger.removeHandler(existing_handler)
4561
existing_handler.close()
4662

@@ -49,7 +65,7 @@ def _apply_console_logging_settings(logging_settings: "LoggingSettings") -> None
4965
"""Set up logging to the console output stream."""
5066
# NOTE: Handlers are replaced rather than reconfigured in place, so that applying
5167
# settings repeatedly (upon every reload) cannot accumulate duplicate handlers.
52-
_remove_handlers_of_type(logger, logging.StreamHandler)
68+
_remove_handlers_of_type(logger, logging.StreamHandler, excluding=logging.FileHandler)
5369

5470
console_logging_handler: Handler = logging.StreamHandler()
5571
console_logging_handler.setFormatter(
@@ -65,7 +81,9 @@ def _apply_discord_channel_logging_settings(logging_settings: "LoggingSettings")
6581
"""Set up relaying of error logs to a Discord log channel."""
6682
_remove_handlers_of_type(logger, DiscordHandler)
6783

68-
DISCORD_CHANNEL_LOGGING_SETTINGS = logging_settings.discord_channel
84+
DISCORD_CHANNEL_LOGGING_SETTINGS: Final[DiscordChannelLoggingSettings | None] = (
85+
logging_settings.discord_channel
86+
)
6987
if DISCORD_CHANNEL_LOGGING_SETTINGS is None:
7088
logger.debug(
7189
"No Discord log-channel webhook-URL was set, "
@@ -89,8 +107,15 @@ def _apply_discord_api_logging_settings(logging_settings: "LoggingSettings") ->
89107
"""Set up recording of the logs emitted by the Discord API wrapper."""
90108
_remove_handlers_of_type(discord_logger, logging.FileHandler)
91109

92-
DISCORD_API_LOGGING_SETTINGS = logging_settings.discord_api
110+
DISCORD_API_LOGGING_SETTINGS: Final[DiscordAPILoggingSettings] = (
111+
logging_settings.discord_api
112+
)
93113
if not DISCORD_API_LOGGING_SETTINGS.enabled:
114+
# NOTE: The level is restored alongside the handler, so that disabling these logs
115+
# after they have been enabled leaves the Discord API logger exactly as it began.
116+
# Leaving a previously configured level in place would otherwise send every record
117+
# meeting it to the root logger, now that propagation has been turned back on.
118+
discord_logger.setLevel(logging.NOTSET)
94119
discord_logger.propagate = True
95120
return
96121

‎config/_schema.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -538,8 +538,8 @@ class CommunityGroupSettings(_BaseSettingsSchema): # type: ignore[explicit-any]
538538
),
539539
json_schema_extra={"requires_restart": False, "secret": False},
540540
)
541-
links: LinksSettings
542-
msl: MSLSettings
541+
links: LinksSettings = Field(default_factory=LinksSettings)
542+
msl: MSLSettings = Field(default_factory=MSLSettings)
543543

544544

545545
class PingCommandSettings(_BaseSettingsSchema): # type: ignore[explicit-any]
@@ -732,7 +732,7 @@ class SettingsSchema(_BaseSettingsSchema): # type: ignore[explicit-any]
732732

733733
logging: LoggingSettings = Field(default_factory=LoggingSettings)
734734
discord: DiscordSettings
735-
community_group: CommunityGroupSettings
735+
community_group: CommunityGroupSettings = Field(default_factory=CommunityGroupSettings)
736736
commands: CommandsSettings = Field(default_factory=CommandsSettings)
737737
reminders: RemindersSettings = Field(default_factory=RemindersSettings)
738738
auto_add_committee_to_threads: bool = Field(

‎tests/config/conftest.py‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,6 @@
4343
discord:
4444
bot-token: {VALID_BOT_TOKEN}
4545
main-guild-id: {VALID_MAIN_GUILD_ID}
46-
community-group:
47-
links: {{}}
48-
msl: {{}}
4946
"""
5047

5148

0 commit comments

Comments
 (0)