2019-08-10 12:15:09 +00:00
|
|
|
"""
|
|
|
|
This module contain functions to load the configuration file
|
|
|
|
"""
|
|
|
|
import logging
|
2020-03-22 19:09:01 +00:00
|
|
|
import re
|
2019-08-10 12:15:09 +00:00
|
|
|
import sys
|
2020-03-22 19:09:01 +00:00
|
|
|
from pathlib import Path
|
2019-08-10 12:15:09 +00:00
|
|
|
from typing import Any, Dict
|
|
|
|
|
2020-03-22 19:09:01 +00:00
|
|
|
import rapidjson
|
2019-08-10 12:15:09 +00:00
|
|
|
|
2020-03-22 19:09:01 +00:00
|
|
|
from freqtrade.exceptions import OperationalException
|
2019-08-10 12:15:09 +00:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2019-08-11 21:32:03 +00:00
|
|
|
CONFIG_PARSE_MODE = rapidjson.PM_COMMENTS | rapidjson.PM_TRAILING_COMMAS
|
|
|
|
|
|
|
|
|
2020-03-22 19:09:01 +00:00
|
|
|
def log_config_error_range(path: str, errmsg: str) -> str:
|
|
|
|
"""
|
|
|
|
Parses configuration file and prints range around error
|
|
|
|
"""
|
|
|
|
if path != '-':
|
|
|
|
offsetlist = re.findall(r'(?<=Parse\serror\sat\soffset\s)\d+', errmsg)
|
|
|
|
if offsetlist:
|
|
|
|
offset = int(offsetlist[0])
|
|
|
|
text = Path(path).read_text()
|
|
|
|
# Fetch an offset of 80 characters around the error line
|
|
|
|
subtext = text[offset-min(80, offset):offset+80]
|
|
|
|
segments = subtext.split('\n')
|
2020-03-23 06:54:27 +00:00
|
|
|
if len(segments) > 3:
|
|
|
|
# Remove first and last lines, to avoid odd truncations
|
|
|
|
return '\n'.join(segments[1:-1])
|
|
|
|
else:
|
|
|
|
return subtext
|
2020-03-22 19:09:01 +00:00
|
|
|
|
|
|
|
|
2019-08-10 12:15:09 +00:00
|
|
|
def load_config_file(path: str) -> Dict[str, Any]:
|
|
|
|
"""
|
|
|
|
Loads a config file from the given path
|
|
|
|
:param path: path as str
|
|
|
|
:return: configuration as dictionary
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
# Read config from stdin if requested in the options
|
|
|
|
with open(path) if path != '-' else sys.stdin as file:
|
2019-08-11 21:32:03 +00:00
|
|
|
config = rapidjson.load(file, parse_mode=CONFIG_PARSE_MODE)
|
2019-08-10 12:15:09 +00:00
|
|
|
except FileNotFoundError:
|
|
|
|
raise OperationalException(
|
|
|
|
f'Config file "{path}" not found!'
|
|
|
|
' Please create a config file or check whether it exists.')
|
2020-03-22 19:09:01 +00:00
|
|
|
except rapidjson.JSONDecodeError as e:
|
|
|
|
err_range = log_config_error_range(path, str(e))
|
|
|
|
raise OperationalException(
|
|
|
|
f'{e}\n'
|
|
|
|
f'Please verify the following segment of your configuration:\n{err_range}'
|
|
|
|
)
|
2019-08-10 12:15:09 +00:00
|
|
|
|
|
|
|
return config
|