kopia lustrzana https://gitlab.com/marnanel/chapeau
rodzic
a4d1e8ed03
commit
5cfdbc45a6
|
@ -1,4 +1,9 @@
|
|||
import argparse
|
||||
import configparser
|
||||
import os
|
||||
|
||||
DEFAULT_CONFIG_FILENAME = '/etc/kepi/kepi.conf'
|
||||
CONFIG_SECTION = 'kepi'
|
||||
|
||||
class Config:
|
||||
|
||||
|
@ -18,11 +23,24 @@ class Config:
|
|||
else:
|
||||
raise KeyError(field)
|
||||
|
||||
def _load_config_file(self, filename):
|
||||
conf = configparser.ConfigParser()
|
||||
conf.read(filename, encoding='UTF-8')
|
||||
|
||||
for option in conf.items(CONFIG_SECTION):
|
||||
self.settings[option] = conf.get(
|
||||
section = CONFIG_SECTION,
|
||||
option = option,
|
||||
)
|
||||
|
||||
def parse_args(self, argparser):
|
||||
|
||||
assert self.subcommands is not None
|
||||
|
||||
self.argparser = argparser
|
||||
argparser.add_argument(
|
||||
'--config', '-C', default=None,
|
||||
help='location of configuration file')
|
||||
|
||||
self.subparsers = argparser.add_subparsers(
|
||||
dest = 'command',
|
||||
|
@ -36,13 +54,17 @@ class Config:
|
|||
|
||||
args = self.argparser.parse_args()
|
||||
|
||||
if args.config is None:
|
||||
if os.path.exists(DEFAULT_CONFIG_FILENAME):
|
||||
self._load_config_file(DEFAULT_CONFIG_FILENAME)
|
||||
else:
|
||||
self._load_config_file(args.config)
|
||||
|
||||
for field in dir(args):
|
||||
if field.startswith('_'):
|
||||
continue
|
||||
self.settings[field] = getattr(args, field)
|
||||
|
||||
# TODO here we will check the config file, and merge them in.
|
||||
|
||||
config = Config.__new__(Config)
|
||||
|
||||
def subcommand(fn):
|
||||
|
|
|
@ -0,0 +1,27 @@
|
|||
import sys
|
||||
import argparse
|
||||
from kepi.config import config, subcommand
|
||||
|
||||
@subcommand
|
||||
def subcommands_for_testing(subparsers):
|
||||
parser = subparsers.add_parser('wombat')
|
||||
|
||||
parser.add_argument(
|
||||
'spong',
|
||||
help=(
|
||||
'the spong to wombat'
|
||||
),
|
||||
)
|
||||
|
||||
def test_config_add_subcommands():
|
||||
|
||||
old_argv = sys.argv
|
||||
sys.argv = ['kepi', 'wombat', 'foo']
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
config.parse_args(parser)
|
||||
|
||||
assert config.command=='wombat'
|
||||
assert config.spong=='foo'
|
||||
|
||||
sys.argv = old_argv
|
Ładowanie…
Reference in New Issue