<s> import json <EOL> import os . path <EOL> from copy import deepcopy <EOL> from twisted . python . filepath import FilePath <EOL> from twisted . python . util import sibpath <EOL> from smartanthill . exception import ConfigKeyError <EOL> from smartanthill . util import load_config , merge_nested_dicts , singleton <EOL> def get_baseconf ( ) : <EOL> return load_config ( sibpath ( __file__ , "<STR_LIT>" ) ) <EOL> @ singleton <EOL> class ConfigProcessor ( object ) : <EOL> def __init__ ( self , wsdir , user_options ) : <EOL> self . wsconfp = FilePath ( os . path . join ( wsdir , "<STR_LIT>" ) ) <EOL> self . _data = get_baseconf ( ) <EOL> self . _wsdata = { } <EOL> self . _process_workspace_conf ( ) <EOL> self . _process_user_options ( user_options ) <EOL> def _process_workspace_conf ( self ) : <EOL> if ( not self . wsconfp . exists ( ) or not <EOL> self . wsconfp . isfile ( ) ) : <EOL> return <EOL> self . _wsdata = load_config ( self . wsconfp . path ) <EOL> self . _data = merge_nested_dicts ( self . _data , deepcopy ( self . _wsdata ) ) <EOL> def _process_user_options ( self , options ) : <EOL> assert isinstance ( options , dict ) <EOL> for k , v in options . iteritems ( ) : <EOL> _dyndict = v <EOL> for p in reversed ( k . split ( "<STR_LIT:.>" ) ) : <EOL> _dyndict = { p : _dyndict } <EOL> self . _data = merge_nested_dicts ( self . _data , _dyndict ) <EOL> def _write_wsconf ( self ) : <EOL> with open ( self . wsconfp . path , "<STR_LIT:w>" ) as f : <EOL> json . dump ( self . _wsdata , f , sort_keys = True , indent = <NUM_LIT:2> ) <EOL> def __contains__ ( self , key ) : <EOL> try : <EOL> self . get ( key ) <EOL> return True <EOL> except : <EOL> return False <EOL> def get ( self , key_path , default = None ) : <EOL> try : <EOL> value = self . _data <EOL> for k in key_path . split ( "<STR_LIT:.>" ) : <EOL> value = value [ k ] <EOL> return value <EOL> except KeyError : <EOL> if default is not None : <EOL> return default <EOL> else : <EOL> raise ConfigKeyError ( key_path ) <EOL> def update ( self , key_path , data , write_wsconf = True ) : <EOL> newdata = data <EOL> for k in reversed ( key_path . split ( "<STR_LIT:.>" ) ) : <EOL> newdata = { k : newdata } <EOL> self . _data = merge_nested_dicts ( self . _data , deepcopy ( newdata ) ) <EOL> self . _wsdata = merge_nested_dicts ( self . _wsdata , newdata ) <EOL> if write_wsconf : <EOL> self . _write_wsconf ( ) <EOL> def delete ( self , key_path , write_wsconf = True ) : <EOL> if "<STR_LIT:.>" in key_path : <EOL> _parts = key_path . split ( "<STR_LIT:.>" ) <EOL> _parent = "<STR_LIT:.>" . join ( _parts [ : - <NUM_LIT:1> ] ) <EOL> _delkey = _parts [ - <NUM_LIT:1> ] <EOL> del self . get ( _parent ) [ _delkey ] <EOL> _tmpwsd = self . _wsdata <EOL> for k in _parent . split ( "<STR_LIT:.>" ) : <EOL> _tmpwsd = _tmpwsd [ k ] <EOL> del _tmpwsd [ _delkey ] <EOL> else : <EOL> del self . _data [ key_path ] <EOL> del self . _wsdata [ key_path ] <EOL> if write_wsconf : <EOL> self . _write_wsconf ( ) </s>
