1 # Copyright (C) 2022 Wind River Systems, Inc.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
19 class Error(Exception):
20 """Base class for cfg exceptions."""
22 def __init__(self, msg=None):
29 class NoSuchOptError(Error, AttributeError):
30 """Raised if an opt which doesn't exist is referenced."""
32 def __init__(self, opt_name, group=None):
33 self.opt_name = opt_name
37 group_name = 'DEFAULT' if self.group is None else self.group.name
38 return "no such option %s in group [%s]" % (self.opt_name, group_name)
41 class NoSuchConfigFile(Error):
42 """Raised if the config file does not exist."""
44 def __init__(self, file_path):
45 self.file_path = file_path
48 return "no such file %s exist" % self.file_path
52 def __init__(self, section: str) -> None:
53 self.group_name = section
56 def _set(self, name, value):
57 opt = getattr(self, name)
59 setattr(self, name, value)
60 if name not in self._options:
61 self._options[name] = value
65 if name in self._options:
66 return self._options[name]
68 def __getattr__(self, name):
70 return self._get(name)
74 raise NoSuchOptError(name, self.group_name)
78 def __init__(self) -> None:
79 self.__cache = {'b': 456}
82 def _set(self, section, name='', value=''):
83 group = getattr(self, section)
85 group = Section(section)
86 setattr(self, section, group)
87 if section not in self._sections:
88 self._sections[section] = group
90 setattr(group, name, value)
94 if name in self._sections:
95 return self._sections(name)
97 if name in self.__cache:
98 return self.__cache(name)
100 def __getattr__(self, name):
102 return self._get(name)
106 raise NoSuchOptError(name)
108 def load(self, file_path):
109 if not os.path.exists(file_path):
110 raise NoSuchConfigFile(file_path)
111 conf = configparser.ConfigParser()
113 default_group = self._set('DEFAULT')
114 for option in conf['DEFAULT']:
116 default_group._set(option, conf['DEFAULT'][option])
117 for section in conf.sections():
118 group = self._set(section)
119 for option in conf[section]:
120 group._set(option, conf[section][option])
123 if __name__ == "__main__":
125 # conf._set('default', 'a', 123)
127 # print(conf.default.a)
130 # conf = configparser.ConfigParser()
131 # conf.read('configs/o2app.conf')
133 # print(conf['DEFAULT'].__dict__)
134 # print(conf['DEFAULT']['test'])
135 conf.load('configs/o2app.conf')
137 print(conf.DEFAULT.test)
138 print(conf.PUBSUB.ooo)
139 print(conf.DEFAULT.oCloudGlobalID)