Create config provider

This commit is contained in:
Maxim Khomutov 2022-09-29 23:53:52 +03:00
parent 05d505e9af
commit c386d2f5f0
4 changed files with 67 additions and 0 deletions

View File

@ -0,0 +1 @@
PyYAML~=6.0

36
src/config_provider.py Normal file
View File

@ -0,0 +1,36 @@
import os
import yaml
import errors
class Config:
def __init__(self, auth=None, game=None, server=None):
self.Auth = auth or {"key": None, "private": True}
self.Game = game or {"map": "gridmap_v2", "players": 8, "max_cars": 1}
self.Server = server or {"name": "KuiToi-Server",
"description": "The best description",
"port": 30814, "custom_ip": None, "debug": False}
def __repr__(self):
return "%s(Auth=%r, Game=%r, Server=%r)" % (self.__class__.__name__, self.Auth, self.Game, self.Server)
class ConfigProvider:
def __init__(self, config_patch):
self.config_patch = config_patch
self.config = Config()
def open_config(self):
if not os.path.exists(self.config_patch):
with open(self.config_patch, "w", encoding="utf-8") as f:
yaml.dump(self.config, f)
try:
with open(self.config_patch, "r", encoding="utf-8") as f:
self.config = yaml.load(f.read(), yaml.Loader)
except yaml.YAMLError:
raise errors.BadConfigError("Your config file can't open as YAML.")
return self.config

4
src/errors.py Normal file
View File

@ -0,0 +1,4 @@
# -*- coding: utf-8 -*-
class BadConfigError(Exception):
...

View File

@ -0,0 +1,26 @@
import argparse
import __version__
import config_provider
parser = argparse.ArgumentParser(description='KuiToi-Server - BeamingDrive server compatible with BeamMP clients!')
parser.add_argument('-v', '--version', action="store_true", help='Print version and exit.', default=False)
parser.add_argument('--config', help='Patch to config file.', nargs='?', default=None, type=str)
def main():
args = parser.parse_args()
if args.version:
print(f"KuiToi-Server:\n\tVersion: {__version__.__version__}\n\tBuild: {__version__.__build__}")
exit(0)
config_patch = "kuitoi.yml"
if args.config:
config_patch = args.config
cp = config_provider.ConfigProvider(config_patch)
config = cp.open_config()
print(config)
if __name__ == '__main__':
main()