comparison sat/tools/config.py @ 2624:56f94936df1e

code style reformatting using black
author Goffi <goffi@goffi.org>
date Wed, 27 Jun 2018 20:14:46 +0200
parents 26edcf3a30eb
children 0fa217fafabf
comparison
equal deleted inserted replaced
2623:49533de4540b 2624:56f94936df1e
19 # along with this program. If not, see <http://www.gnu.org/licenses/>. 19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 20
21 """ Configuration related useful methods """ 21 """ Configuration related useful methods """
22 22
23 from sat.core.log import getLogger 23 from sat.core.log import getLogger
24
24 log = getLogger(__name__) 25 log = getLogger(__name__)
25 26
26 from sat.core.constants import Const as C 27 from sat.core.constants import Const as C
27 from sat.core.i18n import _ 28 from sat.core.i18n import _
28 from sat.core import exceptions 29 from sat.core import exceptions
48 for file_ in C.CONFIG_FILES[::-1]: 49 for file_ in C.CONFIG_FILES[::-1]:
49 # we will eventually update the existing file with the highest priority, if it's a user personal file... 50 # we will eventually update the existing file with the highest priority, if it's a user personal file...
50 if not silent: 51 if not silent:
51 log.debug(_(u"Testing file %s") % file_) 52 log.debug(_(u"Testing file %s") % file_)
52 if os.path.isfile(file_): 53 if os.path.isfile(file_):
53 if file_.startswith(os.path.expanduser('~')): 54 if file_.startswith(os.path.expanduser("~")):
54 config.read([file_]) 55 config.read([file_])
55 target_file = file_ 56 target_file = file_
56 break 57 break
57 if not target_file: 58 if not target_file:
58 # ... otherwise we create a new config file for that user 59 # ... otherwise we create a new config file for that user
59 target_file = BaseDirectory.save_config_path('sat') + '/sat.conf' 60 target_file = BaseDirectory.save_config_path("sat") + "/sat.conf"
60 if section and section.upper() != DEFAULTSECT and not config.has_section(section): 61 if section and section.upper() != DEFAULTSECT and not config.has_section(section):
61 config.add_section(section) 62 config.add_section(section)
62 config.set(section, option, value) 63 config.set(section, option, value)
63 with open(target_file, 'wb') as configfile: 64 with open(target_file, "wb") as configfile:
64 config.write(configfile) # for the next time that user launches sat 65 config.write(configfile) # for the next time that user launches sat
65 if not silent: 66 if not silent:
66 if option in ('passphrase',): # list here the options storing a password 67 if option in ("passphrase",): # list here the options storing a password
67 value = '******' 68 value = "******"
68 log.warning(_(u"Config auto-update: %(option)s set to %(value)s in the file %(config_file)s") % 69 log.warning(
69 {'option': option, 'value': value, 'config_file': target_file}) 70 _(
71 u"Config auto-update: %(option)s set to %(value)s in the file %(config_file)s"
72 )
73 % {"option": option, "value": value, "config_file": target_file}
74 )
75
70 76
71 def parseMainConf(): 77 def parseMainConf():
72 """look for main .ini configuration file, and parse it""" 78 """look for main .ini configuration file, and parse it"""
73 config = SafeConfigParser(defaults=C.DEFAULT_CONFIG) 79 config = SafeConfigParser(defaults=C.DEFAULT_CONFIG)
74 try: 80 try:
75 config.read(C.CONFIG_FILES) 81 config.read(C.CONFIG_FILES)
76 except: 82 except:
77 log.error(_("Can't read main config !")) 83 log.error(_("Can't read main config !"))
78 return config 84 return config
85
79 86
80 def getConfig(config, section, name, default=None): 87 def getConfig(config, section, name, default=None):
81 """Get a configuration option 88 """Get a configuration option
82 89
83 @param config (SafeConfigParser): the configuration instance 90 @param config (SafeConfigParser): the configuration instance
91 """ 98 """
92 if not section: 99 if not section:
93 section = DEFAULTSECT 100 section = DEFAULTSECT
94 101
95 try: 102 try:
96 value = config.get(section, name).decode('utf-8') 103 value = config.get(section, name).decode("utf-8")
97 except (NoOptionError, NoSectionError) as e: 104 except (NoOptionError, NoSectionError) as e:
98 if default is Exception: 105 if default is Exception:
99 raise e 106 raise e
100 return default 107 return default
101 108
102 if name.endswith('_path') or name.endswith('_dir'): 109 if name.endswith("_path") or name.endswith("_dir"):
103 value = os.path.expanduser(value) 110 value = os.path.expanduser(value)
104 # thx to Brian (http://stackoverflow.com/questions/186857/splitting-a-semicolon-separated-string-to-a-dictionary-in-python/186873#186873) 111 # thx to Brian (http://stackoverflow.com/questions/186857/splitting-a-semicolon-separated-string-to-a-dictionary-in-python/186873#186873)
105 elif name.endswith('_list'): 112 elif name.endswith("_list"):
106 value = csv.reader([value], delimiter=',', quotechar='"', skipinitialspace=True).next() 113 value = csv.reader(
107 elif name.endswith('_dict'): 114 [value], delimiter=",", quotechar='"', skipinitialspace=True
115 ).next()
116 elif name.endswith("_dict"):
108 try: 117 try:
109 value = json.loads(value) 118 value = json.loads(value)
110 except ValueError as e: 119 except ValueError as e:
111 raise exceptions.ParsingError(u"Error while parsing data: {}".format(e)) 120 raise exceptions.ParsingError(u"Error while parsing data: {}".format(e))
112 if not isinstance(value, dict): 121 if not isinstance(value, dict):
113 raise exceptions.ParsingError(u"{name} value is not a dict: {value}".format(name=name, value=value)) 122 raise exceptions.ParsingError(
114 elif name.endswith('_json'): 123 u"{name} value is not a dict: {value}".format(name=name, value=value)
124 )
125 elif name.endswith("_json"):
115 try: 126 try:
116 value = json.loads(value) 127 value = json.loads(value)
117 except ValueError as e: 128 except ValueError as e:
118 raise exceptions.ParsingError(u"Error while parsing data: {}".format(e)) 129 raise exceptions.ParsingError(u"Error while parsing data: {}".format(e))
119 return value 130 return value