pumpkin/config.py

78 lines
1.6 KiB
Python

#!/usr/bin/env python3
class Config:
def __init__(self, file):
self.COMMENT_MARK = '#'
self.path = file
try:
with open(file, 'r') as conf:
config = conf.read().split('\n')
except:
raise IOError('Couldn\'t read ' + file + '!')
if not self.isValidFile(config):
raise Exception('Error: ' + file + ' is no valid config file!')
self.values = {}
for c in config:
if self.lineHasValue(c):
parts = c.split('=')
self.values[parts[0].strip()] = parts[1].strip()
def getValue(self, key):
try:
return self.values[key]
except:
return None
def getInt(self, key):
value = self.getValue(key)
if value == None:
return None
return int(value)
def getFloat(self, key):
return float(self.getValue(key))
def getBool(self, key):
return bool(self.getValue(key))
def getString(self, key):
return self.getValue(key)
def getList(self, key):
values = []
for v in self.getValue(key).split(','):
values.append(v.strip())
return values
def getIntList(self, key):
values = []
for i in self.getList(key):
values.append(int(i))
return values
def lineHasValue(self, line):
return not line.startswith(self.COMMENT_MARK) and len(line.replace(' ', '').replace('\n', '')) > 0 and line.count('=') == 1
def lineHasSyntaxError(self, line):
return not line.startswith(self.COMMENT_MARK) and len(line.replace(' ', '').replace('\n', '')) > 0 and line.count('=') != 1
def isValidFile(self, config):
count = 1
for line in config:
if self.lineHasSyntaxError(line):
print(self.path + ' Line ' + str(count) + ': Invalid syntax!')
count += 1
return True