6 from sfa.util.xml import XML
14 def __init__(self, config_file='/etc/sfa/sfa_config'):
15 self.config = ConfigParser.ConfigParser()
16 self.filename = config_file
17 if not os.path.isfile(self.filename):
18 self.create(self.filename)
19 self.load(self.filename)
21 def create(self, filename):
22 if not os.path.exists(os.path.dirname(filename)):
23 os.makedirs(os.path.dirname(filename))
24 configfile = open(filename, 'w')
25 configfile.write(default_config)
29 def load(self, filename):
31 if filename.endswith('.xml'):
33 self.load_xml(filename)
36 self.config.read(filename)
38 self.config.read(filename)
41 def load_xml(self, filename):
43 categories = xml.xpath('//configuration/variables/category')
44 for category in categories:
45 section_name = category.get('id')
46 if not self.config.has_section(section_name):
47 self.config.add_section(section_name)
48 options = category.xpath('./variablelist/variable')
49 for option in options:
50 option_name = option.get('id')
51 value = option.xpath('./value')[0].text
54 self.config.set(section_name, option_name, value)
57 def locate_varname(self, varname):
58 varname = varname.lower()
59 sections = self.config.sections()
62 for section in sections:
63 if varname.startswith(section.lower()) and len(section) > len(section_name):
64 section_name = section.lower()
65 var_name = varname.replace(section_name, "")[1:]
66 if not self.config.has_option(section_name, var_name):
67 raise ConfigParser.NoOptionError(varname, section_name)
68 return (section_name, var_name)
70 def set_attributes(self):
71 sections = self.config.sections()
72 for section in sections:
73 for item in self.config.items(section):
74 name = "%s_%s" % (section, item[0])
76 setattr(self, name, value)
77 setattr(self, name.upper(), value)
80 def verify(self, config1, config2, validate_method):
83 def validate_type(self, var_type, value):
86 def dump(self, sections = []):
88 sections = self.config.sections()
90 for section in sections:
91 print "[%s]" % section
92 for item in self.config.items(section):
93 print "%s=%s" % (item[0], item[1])
96 def write(self, filename=None):
98 filename = self.filename
99 configfile = open(filename, 'w')
100 self.config.write(configfile)
102 def save(self, filename=None):
105 def __getattr__(self, attr):
106 return getattr(self.config, attr)
108 if __name__ == '__main__':
110 if len(sys.argv) > 1:
111 filename = sys.argv[1]
112 config = Config(filename)