From cef55459c64ba4678a3857a90888f463c3f1e3d5 Mon Sep 17 00:00:00 2001 From: Vexed Date: Sat, 25 Dec 2021 02:02:44 +0000 Subject: [PATCH] Fix issues with loading config.json when it doesn't exist (#5416) * catch and handle FileNotFoundError when using --no-instance when config.json does not already exist * move load_existing_config to data_manager.py * use load_existing_config in create_temp_config * Fix import in redbot-launcher Co-authored-by: jack1142 <6032823+jack1142@users.noreply.github.com> --- redbot/core/data_manager.py | 18 ++++++++++++++++-- redbot/launcher.py | 2 +- redbot/setup.py | 13 ++----------- 3 files changed, 19 insertions(+), 14 deletions(-) diff --git a/redbot/core/data_manager.py b/redbot/core/data_manager.py index 1472d9dce..307fa606f 100644 --- a/redbot/core/data_manager.py +++ b/redbot/core/data_manager.py @@ -46,6 +46,21 @@ if not config_dir: config_file = config_dir / "config.json" +def load_existing_config(): + """Get the contents of the config file, or an empty dictionary if it does not exist. + + Returns + ------- + dict + The config data. + """ + if not config_file.exists(): + return {} + + with config_file.open(encoding="utf-8") as fs: + return json.load(fs) + + def create_temp_config(): """ Creates a default instance for Red, so it can be ran @@ -61,8 +76,7 @@ def create_temp_config(): default_dirs["STORAGE_TYPE"] = "JSON" default_dirs["STORAGE_DETAILS"] = {} - with config_file.open("r", encoding="utf-8") as fs: - config = json.load(fs) + config = load_existing_config() config[name] = default_dirs diff --git a/redbot/launcher.py b/redbot/launcher.py index 8a29199f3..f7382078c 100644 --- a/redbot/launcher.py +++ b/redbot/launcher.py @@ -16,13 +16,13 @@ import pkg_resources from redbot import MIN_PYTHON_VERSION from redbot.setup import ( basic_setup, - load_existing_config, remove_instance, remove_instance_interaction, create_backup, ) from redbot.core import __version__, version_info as red_version_info, VersionInfo from redbot.core.cli import confirm +from redbot.core.data_manager import load_existing_config if sys.platform == "linux": import distro # pylint: disable=import-error diff --git a/redbot/setup.py b/redbot/setup.py index cd0bc32b6..57baccb70 100644 --- a/redbot/setup.py +++ b/redbot/setup.py @@ -37,16 +37,7 @@ except PermissionError: sys.exit(1) config_file = config_dir / "config.json" - -def load_existing_config(): - if not config_file.exists(): - return {} - - with config_file.open(encoding="utf-8") as fs: - return json.load(fs) - - -instance_data = load_existing_config() +instance_data = data_manager.load_existing_config() if instance_data is None: instance_list = [] else: @@ -54,7 +45,7 @@ else: def save_config(name, data, remove=False): - _config = load_existing_config() + _config = data_manager.load_existing_config() if remove and name in _config: _config.pop(name) else: