Make use of ruamel DuplicateKeyError exception

This commit is contained in:
Jonathan van der Steege 2022-06-20 22:48:59 +02:00
parent 08f46b2f31
commit 18bae71d95
2 changed files with 18 additions and 12 deletions

View file

@ -6,6 +6,7 @@ import os
import colorama import colorama
from ruamel.yaml import YAML from ruamel.yaml import YAML
from ruamel.yaml import constructor
import xdg.BaseDirectory import xdg.BaseDirectory
from . import __version__ from . import __version__
@ -162,21 +163,25 @@ def verify_config_colors(config):
def load_config(config_path): def load_config(config_path):
"""Tries to load a config file from YAML.""" """Tries to load a config file from YAML."""
# If duplicate keys at same level in config file, print warning try:
duplicate_keys = config_duplicate_keys(config_path) with open(config_path, encoding=YAML_FILE_ENCODING) as f:
if duplicate_keys: yaml = YAML(typ="safe")
yaml.allow_duplicate_keys = False
return yaml.load(f)
except constructor.DuplicateKeyError as e:
print_msg( print_msg(
Message( Message(
MsgText.ConfigDoubleKeys, MsgText.ConfigDoubleKeys,
MsgStyle.WARNING, MsgStyle.WARNING,
{"duplicate_keys": duplicate_keys}, {
"error_message": e,
},
) )
) )
with open(config_path, encoding=YAML_FILE_ENCODING) as f:
with open(config_path, encoding=YAML_FILE_ENCODING) as f: yaml = YAML(typ="safe")
yaml = YAML(typ="safe") yaml.allow_duplicate_keys = True
yaml.allow_duplicate_keys = True return yaml.load(f)
return yaml.load(f)
def is_config_json(config_path): def is_config_json(config_path):

View file

@ -198,9 +198,10 @@ class MsgText(Enum):
ConfigDoubleKeys = """ ConfigDoubleKeys = """
Warning: One or more keys appear multiple times at the same level Warning: One or more keys appear multiple times at the same level
in your configuration file: in your configuration file.
{duplicate_keys}
""" {error_message}
"""
# --- Password --- # # --- Password --- #
Password = "Password:" Password = "Password:"