-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconfig_file_parser.py
104 lines (79 loc) · 2.99 KB
/
config_file_parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
##
## Copyright 2017 SRI International
## See COPYING file distributed along with the package for the copyright and license terms
##
"""
Parse Arguments From Config File
"""
from builtins import object
import os
import yaml
from collections import OrderedDict
def __ordered_load__(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
class OrderedLoader(Loader):
pass
def construct_mapping(loader, node):
loader.flatten_mapping(node)
return object_pairs_hook(loader.construct_pairs(node))
OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_mapping)
return yaml.load(stream, OrderedLoader)
class config_file_parser(object):
"""
config_file_parser Object
====================
Main object that provides access to config file
config_file: yml file specifying configuration
Or set path as SIBIS_CONFIG environment variable
(default: default_config_file)
assumes
import config_file_parser
cfp = config_file_parser()
err_msg = cfp.config()
is called initially
"""
def __init__(self):
self.__config_dict = None
self.__config_file = None
def configure(self, config_file=None, ordered_load=False):
"""
Configures the session object by first checking for an
environment variable, then in the home directory.
"""
if config_file :
self.__config_file = config_file
else :
env = os.environ.get('SIBIS_CONFIG')
if env:
self.__config_file = env
else:
self.__config_file = os.path.join('/', *'/fs/storage/share/operations/secrets/.sibis/'.split('/'), '.sibis-general-config.yml')
try:
with open(self.__config_file, 'r') as fi:
if ordered_load:
self.__config_dict = __ordered_load__(fi, yaml.SafeLoader)
else :
self.__config_dict = yaml.safe_load(fi)
except IOError as err:
return err
return None
def get_value(self,category,subject=None):
cfg = self.get_category(category)
if cfg and subject:
return cfg.get(subject)
return cfg
def get_category(self,category):
if not self.__config_dict :
raise RuntimeError("Please run configure first before calling this function!")
return self.__config_dict.get(category)
def has_category(self,category):
if not self.__config_dict:
raise RuntimeError("Please run configure first before calling this function!")
return category in self.__config_dict
def keys(self):
if not self.__config_dict :
raise RuntimeError("Please run configure first before calling this function!")
return list(self.__config_dict.keys())
def get_config_file(self):
return self.__config_file