Skip to content

Commit

Permalink
41: display error message when config.yml is not loaded
Browse files Browse the repository at this point in the history
This will only be shown when the user has specified a config.yml
file using the command line.  The error will print out the
full path to the file that was not found.

Also, bump version numbers to 0.1.10.
  • Loading branch information
chrisrude committed Jun 4, 2023
1 parent 706275c commit 95cc194
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 17 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "oobabot"
version = "0.1.9"
version = "0.1.10"
description = "A Discord bot which talks to Large Language Model AIs running on oobabooga's text-generation-webui"
authors = ["Christopher Rude <chris@rudesoftware.net>"]
license = "MIT"
Expand Down
2 changes: 1 addition & 1 deletion src/oobabot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
"""

# todo: sync this up automatically
__version__ = "0.1.9"
__version__ = "0.1.10"
18 changes: 15 additions & 3 deletions src/oobabot/oobabot.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import discord

import oobabot
from oobabot import bot_commands
from oobabot import decide_to_respond
from oobabot import discord_bot
Expand Down Expand Up @@ -67,7 +68,14 @@ def __init__(
self.startup_lock = threading.Lock()
self.settings = settings.Settings()

self.settings.load(cli_args)
try:
self.settings.load(cli_args)
except settings.SettingsError as err:
print("\n".join([str(arg) for arg in list(err.args)]), file=sys.stderr)
if self._our_own_main():
sys.exit(1)
else:
raise

def start(self):
"""
Expand Down Expand Up @@ -238,8 +246,12 @@ def exit_handler(signum, _frame):
signal.signal(signal.SIGTERM, exit_handler)

def _prepare_connections(self):
########################################################
# Test connection to services
"""
Test connections to services, and prepare them for use.
"""
fancy_logger.get().info(
"Starting oobabot, core version %s", oobabot.__version__
)
for client in [self.ooba_client, self.stable_diffusion_client]:
if client is None:
continue
Expand Down
14 changes: 12 additions & 2 deletions src/oobabot/overengineered_settings_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@
DIVIDER = "# " * (YAML_WIDTH >> 1)
INDENT_UNIT = 2


class ConfigFileMissingError(Exception):
"""
Raised when the config file is missing.
"""


SettingDictType = typing.Dict[
str, typing.Union[bool, int, float, str, typing.List[str]]
]
Expand Down Expand Up @@ -359,7 +366,6 @@ def load_from_dict(
"""
Load settings from a dictionary
"""
print(f"settings_dict: {settings_dict}")
for group in setting_groups:
group.set_values_from_dict(settings_dict)

Expand All @@ -368,6 +374,7 @@ def load(
cli_args: typing.List[str],
setting_groups: typing.List["ConfigSettingGroup"],
config_file: str,
raise_if_file_missing: bool,
) -> argparse.ArgumentParser:
"""
Load settings from defaults, config.yml, and command line arguments
Expand All @@ -376,7 +383,10 @@ def load(
Returns the argparse parser, which can be used to print out the help
message.
"""
load_from_yaml(config_file, setting_groups)
load_error_message = load_from_yaml(config_file, setting_groups)
if load_error_message and raise_if_file_missing:
raise ConfigFileMissingError(load_error_message)

namespace = load_from_cli(cli_args, setting_groups)

# returning this since it can print out the help message
Expand Down
45 changes: 35 additions & 10 deletions src/oobabot/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@
import oobabot.overengineered_settings_parser as oesp


class SettingsError(Exception):
"""
Base class for exceptions in this module.
"""

def __init__(self, message: str, cause: Exception = None):
self.message = message
super().__init__(message, cause)


def _console_wrapped(message):
width = shutil.get_terminal_size().columns
return "\n".join(textwrap.wrap(message, width))
Expand Down Expand Up @@ -649,10 +659,13 @@ def write_to_stream(self, out_stream) -> None:
def write_to_file(self, filename: str) -> None:
oesp.write_to_file(self.setting_groups, filename)

def _filename_from_args(self, args: typing.List[str]) -> str:
def _filename_from_args(self, args: typing.List[str]) -> typing.Tuple[str, bool]:
"""
Get the configuration filename from the command line arguments.
If none is supplied, return the default.
Returns a tuple with the file to open, and True if it came
from the default, rather than a CLI argument.
"""

# we need to hack this in here because we want to know the filename
Expand All @@ -663,10 +676,10 @@ def _filename_from_args(self, args: typing.List[str]) -> str:
for config_flag in config_setting.cli_args:
# find the element after config_flag in args
try:
return args[args.index(config_flag) + 1]
return (args[args.index(config_flag) + 1], False)
except (ValueError, IndexError):
continue
return config_setting.default
return (config_setting.default, True)

def load_from_yaml_stream(self, stream: typing.TextIO) -> typing.Optional[str]:
"""
Expand Down Expand Up @@ -696,16 +709,28 @@ def load(
cli_args is intended to be used when running from a standalone
application, while config_file is intended to be used when
running from inside another process.
raises SettingsError if a specific configuration file
was requested (either by the config_file argument or the CLI),
but it could not be found.
"""

is_default = False
if config_file is None:
config_file = self._filename_from_args(cli_args)

self.arg_parser = oesp.load(
cli_args=cli_args,
setting_groups=self.setting_groups,
config_file=config_file,
)
config_file, is_default = self._filename_from_args(cli_args)

try:
self.arg_parser = oesp.load(
cli_args=cli_args,
setting_groups=self.setting_groups,
config_file=config_file,
raise_if_file_missing=not is_default,
)
except oesp.ConfigFileMissingError as err:
# get full path to config_file
config_file = os.path.abspath(config_file)
msg = f"Could not load config file at: {config_file}"
raise SettingsError(msg, err) from err

def print_help(self):
"""
Expand Down

0 comments on commit 95cc194

Please sign in to comment.