2015-12-07 02:40:13 +01:00
"""
conf . py - PyLink configuration core .
2016-06-21 19:56:53 +02:00
This module is used to access the configuration of the current PyLink instance .
It provides simple checks for validating and loading YAML - format configurations from arbitrary files .
2015-12-07 02:40:13 +01:00
"""
2016-07-20 02:45:43 +02:00
try :
import yaml
except ImportError :
raise ImportError ( " Please install PyYAML and try again. " )
2015-08-04 04:27:19 +02:00
import sys
2015-08-29 04:27:38 +02:00
from collections import defaultdict
2016-06-21 03:18:54 +02:00
from . import world
2015-05-31 21:20:09 +02:00
2016-06-25 23:37:06 +02:00
conf = { ' bot ' :
{
' nick ' : ' PyLink ' ,
' user ' : ' pylink ' ,
' realname ' : ' PyLink Service Client ' ,
' serverdesc ' : ' Unconfigured PyLink '
} ,
' logging ' :
{
' stdout ' : ' INFO '
} ,
' servers ' :
# Wildcard defaultdict! This means that
# any network name you try will work and return
# this basic template:
defaultdict ( lambda : { ' ip ' : ' 0.0.0.0 ' ,
' port ' : 7000 ,
' recvpass ' : " unconfigured " ,
' sendpass ' : " unconfigured " ,
' protocol ' : " null " ,
' hostname ' : " pylink.unconfigured " ,
' sid ' : " 000 " ,
' maxnicklen ' : 20 ,
' sidrange ' : ' 0## '
} )
}
confname = ' unconfigured '
2015-09-28 20:30:51 +02:00
def validateConf ( conf ) :
""" Validates a parsed configuration dict. """
assert type ( conf ) == dict , " Invalid configuration given: should be type dict, not %s . " % type ( conf ) . __name__
2016-02-08 03:01:12 +01:00
for section in ( ' bot ' , ' servers ' , ' login ' , ' logging ' ) :
2015-09-28 20:30:51 +02:00
assert conf . get ( section ) , " Missing %r section in config. " % section
2016-02-08 03:01:12 +01:00
2015-09-28 20:30:51 +02:00
assert type ( conf [ ' login ' ] . get ( ' password ' ) ) == type ( conf [ ' login ' ] . get ( ' user ' ) ) == str and \
conf [ ' login ' ] [ ' password ' ] != " changeme " , " You have not set the login details correctly! "
2016-02-08 03:01:12 +01:00
2015-09-28 20:30:51 +02:00
return conf
2016-06-21 20:31:39 +02:00
def loadConf ( filename , errors_fatal = True ) :
2015-09-28 20:30:51 +02:00
""" Loads a PyLink configuration file from the filename given. """
2016-06-21 20:31:39 +02:00
global confname , conf , fname
fname = filename
confname = filename . split ( ' . ' , 1 ) [ 0 ]
2016-07-20 02:40:22 +02:00
try :
with open ( filename , ' r ' ) as f :
2015-09-28 20:30:51 +02:00
conf = yaml . load ( f )
2016-06-21 19:55:42 +02:00
conf = validateConf ( conf )
2016-07-20 02:40:22 +02:00
except Exception as e :
print ( ' ERROR: Failed to load config from %r : %s : %s ' % ( filename , type ( e ) . __name__ , e ) , file = sys . stderr )
print ( ' Users upgrading from users < 0.9-alpha1 should note that the default configuration has been renamed to *pylink.yml*, not *config.yml* ' , file = sys . stderr )
if errors_fatal :
sys . exit ( 4 )
raise
else :
return conf