copy any missing parts of config from .example

This commit is contained in:
sqlcoder 2010-08-29 12:46:22 +01:00
parent 8f91adc513
commit bf8b826bbc

View File

@ -82,6 +82,11 @@ def get_exec_path():
def get_config(file_name, fallback = True): def get_config(file_name, fallback = True):
"""Looks in cwd and in self.default_config_path for a config file.""" """Looks in cwd and in self.default_config_path for a config file."""
# look for example file even if not used here, path is returned to caller
config_found,example_found,example_copy = False,False,False
config_path, example_path = None,None
exec_dir = get_exec_path() exec_dir = get_exec_path()
if file_name == 'logging.conf' and not hasattr(sys, "frozen"): if file_name == 'logging.conf' and not hasattr(sys, "frozen"):
config_path = os.path.join(exec_dir, 'pyfpdb', file_name) config_path = os.path.join(exec_dir, 'pyfpdb', file_name)
@ -89,17 +94,13 @@ def get_config(file_name, fallback = True):
config_path = os.path.join(exec_dir, file_name) config_path = os.path.join(exec_dir, file_name)
# print "config_path=", config_path # print "config_path=", config_path
if os.path.exists(config_path): # there is a file in the cwd if os.path.exists(config_path): # there is a file in the cwd
return (config_path,False) # so we use it config_found = True # so we use it
else: # no file in the cwd, look where it should be in the first place else: # no file in the cwd, look where it should be in the first place
default_dir = get_default_config_path() default_dir = get_default_config_path()
config_path = os.path.join(default_dir, file_name) config_path = os.path.join(default_dir, file_name)
# print "config path 2=", config_path # print "config path 2=", config_path
if os.path.exists(config_path): if os.path.exists(config_path):
return (config_path,False) config_found = True
# No file found
if not fallback:
return (False,False)
# Example configuration for debian package # Example configuration for debian package
if os.name == 'posix': if os.name == 'posix':
@ -108,38 +109,43 @@ def get_config(file_name, fallback = True):
# the config directory for us so there's no need to check it # the config directory for us so there's no need to check it
# again # again
example_path = '/usr/share/python-fpdb/' + file_name + '.example' example_path = '/usr/share/python-fpdb/' + file_name + '.example'
if not config_found and fallback:
try: try:
shutil.copyfile(example_path, config_path) shutil.copyfile(example_path, config_path)
example_copy = True
msg = _("Config file has been created at %s.\n") % config_path msg = _("Config file has been created at %s.\n") % config_path
logging.info(msg) logging.info(msg)
return (config_path,False)
except IOError: except IOError:
pass pass
# OK, fall back to the .example file, should be in the start dir # OK, fall back to the .example file, should be in the start dir
if os.path.exists(file_name + ".example"): elif os.path.exists(file_name + ".example"):
try: try:
print "" print ""
example_path = file_name + ".example"
check_dir(default_dir) check_dir(default_dir)
shutil.copyfile(file_name + ".example", config_path) if not config_found and fallback:
shutil.copyfile(example_path, config_path)
example_copy = True
msg = _("No %s found\n in %s\n or %s\n") % (file_name, exec_dir, default_dir) \ msg = _("No %s found\n in %s\n or %s\n") % (file_name, exec_dir, default_dir) \
+ _("Config file has been created at %s.\n") % config_path + _("Config file has been created at %s.\n") % config_path
print msg print msg
logging.info(msg) logging.info(msg)
file_name = config_path
except: except:
print _("Error copying .example file, cannot fall back. Exiting.\n") print _("Error copying .example file, cannot fall back. Exiting.\n")
sys.stderr.write(_("Error copying .example file, cannot fall back. Exiting.\n")) sys.stderr.write(_("Error copying .example file, cannot fall back. Exiting.\n"))
sys.stderr.write( str(sys.exc_info()) ) sys.stderr.write( str(sys.exc_info()) )
sys.exit() sys.exit()
else: elif fallback:
print _("No %s found, cannot fall back. Exiting.\n") % file_name print _("No %s found, cannot fall back. Exiting.\n") % file_name
sys.stderr.write(_("No %s found, cannot fall back. Exiting.\n") % file_name) sys.stderr.write(_("No %s found, cannot fall back. Exiting.\n") % file_name)
sys.exit() sys.exit()
return (file_name,True)
#print "get_config: returning "+str( (config_path,example_copy,example_path) )
return (config_path,example_copy,example_path)
def get_logger(file_name, config = "config", fallback = False, log_dir=None, log_file=None): def get_logger(file_name, config = "config", fallback = False, log_dir=None, log_file=None):
(conf_file,copied) = get_config(file_name, fallback = fallback) (conf_file,copied,example_file) = get_config(file_name, fallback = fallback)
if log_dir is None: if log_dir is None:
log_dir = os.path.join(get_exec_path(), u'log') log_dir = os.path.join(get_exec_path(), u'log')
@ -674,7 +680,7 @@ class Config:
sys.stderr.write(_("Configuration file %s not found. Using defaults.") % (file)) sys.stderr.write(_("Configuration file %s not found. Using defaults.") % (file))
file = None file = None
if file is None: (file,self.example_copy) = get_config("HUD_config.xml", True) if file is None: (file,self.example_copy,example_file) = get_config("HUD_config.xml", True)
self.file = file self.file = file
self.dir_self = get_exec_path() self.dir_self = get_exec_path()
@ -685,12 +691,25 @@ class Config:
self.log_file = os.path.join(self.dir_log, u'fpdb-log.txt') self.log_file = os.path.join(self.dir_log, u'fpdb-log.txt')
log = get_logger("logging.conf", "config", log_dir=self.dir_log) log = get_logger("logging.conf", "config", log_dir=self.dir_log)
# Parse even if there was no real config file found and we are using the example self.supported_sites = {}
# If using the example, we'll edit it later self.supported_games = {}
self.supported_databases = {} # databaseName --> Database instance
self.aux_windows = {}
self.hhcs = {}
self.popup_windows = {}
self.db_selected = None # database the user would like to use
self.general = General()
self.emails = {}
self.gui_cash_stats = GUICashStats()
added,n = 1,0 # use n to prevent infinite loop if add_missing_elements() fails somehow
while added > 0 and n < 2:
n = n + 1
log.info(_("Reading configuration file %s") % file) log.info(_("Reading configuration file %s") % file)
print _("\nReading configuration file %s\n") % file print _("\nReading configuration file %s\n") % file
try: try:
doc = xml.dom.minidom.parse(file) doc = xml.dom.minidom.parse(file)
self.doc = doc
self.file_error = None self.file_error = None
except: except:
log.error(_("Error parsing %s. See error log file.") % (file)) log.error(_("Error parsing %s. See error log file.") % (file))
@ -705,17 +724,9 @@ class Config:
#sys.exc_info = (<class 'xml.parsers.expat.ExpatError'>, ExpatError('not well-formed (invalid token): line 511, #sys.exc_info = (<class 'xml.parsers.expat.ExpatError'>, ExpatError('not well-formed (invalid token): line 511,
# column 4',), <traceback object at 0x024503A0>) # column 4',), <traceback object at 0x024503A0>)
self.doc = doc if not self.example_copy and example_file is not None:
self.supported_sites = {} # reads example file and adds missing elements into current config
self.supported_games = {} added = self.add_missing_elements(doc, example_file)
self.supported_databases = {} # databaseName --> Database instance
self.aux_windows = {}
self.hhcs = {}
self.popup_windows = {}
self.db_selected = None # database the user would like to use
self.general = General()
self.emails = {}
self.gui_cash_stats = GUICashStats()
if doc.getElementsByTagName("general") == []: if doc.getElementsByTagName("general") == []:
self.general.get_defaults() self.general.get_defaults()
@ -792,7 +803,7 @@ class Config:
self.set_db_parameters(db_name = 'fpdb', db_ip = df_parms['db-host'], self.set_db_parameters(db_name = 'fpdb', db_ip = df_parms['db-host'],
db_user = df_parms['db-user'], db_user = df_parms['db-user'],
db_pass = df_parms['db-password']) db_pass = df_parms['db-password'])
self.save(file=os.path.join(self.default_config_path, "HUD_config.xml")) self.save(file=os.path.join(self.dir_config, "HUD_config.xml"))
if doc.getElementsByTagName("raw_hands") == []: if doc.getElementsByTagName("raw_hands") == []:
self.raw_hands = RawHands() self.raw_hands = RawHands()
@ -807,6 +818,40 @@ class Config:
print "" print ""
#end def __init__ #end def __init__
def add_missing_elements(self, doc, example_file):
""" Look through example config file and add any elements that are not in the config
May need to add some 'enabled' attributes to turn things off - can't just delete a
config section now because this will add it back in"""
nodes_added = 0
try:
example_doc = xml.dom.minidom.parse(example_file)
except:
log.error(_("Error parsing example file %s. See error log file.") % (example_file))
return nodes_added
for cnode in doc.getElementsByTagName("FreePokerToolsConfig"):
for example_cnode in example_doc.childNodes:
if example_cnode.localName == "FreePokerToolsConfig":
for e in example_cnode.childNodes:
#print "nodetype", e.nodeType, "name", e.localName, "found", len(doc.getElementsByTagName(e.localName))
if e.nodeType == e.ELEMENT_NODE and doc.getElementsByTagName(e.localName) == []:
new = doc.importNode(e, True) # True means do deep copy
t_node = self.doc.createTextNode(" ")
cnode.appendChild(t_node)
cnode.appendChild(new)
t_node = self.doc.createTextNode("\r\n\r\n")
cnode.appendChild(t_node)
print "... adding missing config section: " + e.localName
nodes_added = nodes_added + 1
if nodes_added > 0:
print "Added %d missing config sections\n" % nodes_added
self.save()
return nodes_added
def set_hhArchiveBase(self, path): def set_hhArchiveBase(self, path):
self.imp.node.setAttribute("hhArchiveBase", path) self.imp.node.setAttribute("hhArchiveBase", path)