Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
self.option_handlers.append(ServerIdOptionHandler(duid=self.server_duid))
self.option_handlers.append(ClientIdOptionHandler())
self.option_handlers.append(InterfaceIdOptionHandler())
# Add the ones from the configuration
for section_name in self.config.sections():
parts = section_name.split(' ')
if parts[0] != 'option':
# Not an option
continue
option_handler_name = parts[1]
option_handler_id = len(parts) > 2 and parts[2] or None
option_handler_class = option_handler_registry.get(option_handler_name)
if not option_handler_class or not issubclass(option_handler_class, OptionHandler):
raise configparser.ParsingError("Unknown option handler: {}".format(option_handler_name))
logger.debug("Creating {} from config".format(option_handler_class.__name__))
option = option_handler_class.from_config(self.config[section_name], option_handler_id=option_handler_id)
self.option_handlers.append(option)
# Add cleanup handlers so they run last in the handling phase
self.option_handlers.append(UnansweredIAOptionHandler())
self.option_handlers.append(UnansweredIAPDOptionHandler())
# Confirm/Release/Decline messages always need a status
self.option_handlers.append(ConfirmStatusOptionHandler())
self.option_handlers.append(ReleaseStatusOptionHandler())
self.option_handlers.append(DeclineStatusOptionHandler())
def write_config(serial, cert_file=None, ip=None, name=None, guid=None, clear=True):
home = Path.home()
config_file = str(home / ".anki_vector" / "sdk_config.ini")
print("Writing config file to '{}'...".format(colored(config_file, "cyan")))
config = configparser.ConfigParser(strict=False)
try:
config.read(config_file)
except configparser.ParsingError:
if os.path.exists(config_file):
os.rename(config_file, config_file + "-error")
if clear:
config[serial] = {}
if cert_file:
config[serial]["cert"] = cert_file
if ip:
config[serial]["ip"] = ip
if name:
config[serial]["name"] = name
if guid:
config[serial]["guid"] = guid.decode("utf-8")
temp_file = config_file + "-temp"
if os.path.exists(config_file):
os.rename(config_file, temp_file)
try:
"""
try:
log.debug('Loading options file...')
self._loadOptionsFile()
self.synthesisers = Options.readOptionsPaths(
self._options,
'synthesis executables',
transform=lambda x: os.path.expandvars(x),
)
self.simulators = Options.readOptionsPaths(
self._options,
'simulation executables',
transform=lambda x: os.path.expandvars(x),
)
log.debug('...done loading options file')
except (configparser.ParsingError):
log.error(
'The Options file is badly formatted, ' +
'parsing failed with the ' +
'following error:'
)
log.error(traceback.format_exc())
func_types = {}
for _, cls in inspect.getmembers(functions):
if callable(cls):
try:
func_types[cls._name] = cls
except AttributeError:
pass
self.args.first_run = True
config_file = CoqConfigParser()
if os.path.exists(self.cfg.config_path) and read_file:
logging.info("Using configuration file %s" % self.cfg.config_path)
try:
config_file.read(self.cfg.config_path)
except (IOError, TypeError, ParsingError) as e:
s = "Configuration file {} could not be read."
warnings.warn(s.format(cfg.config_path))
raise ConfigurationError((str(e).replace("\\n", "\n")
.replace("\n", "<br>")))
else:
self.args.first_run = False
for x in ["main", "sql", "gui", "output", "filter", "context",
"links", "reference_corpora", "functions", "groups"]:
if x not in config_file.sections():
config_file.add_section(x)
# read SQL configuration:
connection_dict = defaultdict(dict)
for name, value in config_file.items("sql"):
if name.startswith("config_"):
if commandline_config:
configfiles.append(commandline_config)
# Error message, gets filled with invalid sections in the user's configfile.
# If any exist, a popup is displayed at startup.
message = ""
# Let ConfigParser parse the list of configuration files
config = configparser.ConfigParser()
try:
config.read(configfiles)
except UnicodeDecodeError as e:
message += "Could not decode configfile.\n" + str(e)
except configparser.MissingSectionHeaderError as e:
message += "Invalid configfile.\n" + str(e)
except configparser.ParsingError as e:
message += str(e)
# Override settings with settings in config
for header in ["GENERAL", "LIBRARY", "EDIT"]:
if header not in config:
continue
section = config[header]
for setting in section:
try:
settings.override(setting, section[setting])
except StringConversionError as e:
message += str(e) + "\n"
except SettingNotFoundError:
message += "Unknown setting %s\n" % (setting)
# Receive aliases
if os.path.isdir(dir_path):
shutil.rmtree(dir_path, ignore_errors=True)
elif os.path.isfile(dir_path):
os.unlink(dir_path)
# Remove .state torrent resume files
resume_dir = os.path.join(state_dir, "dlcheckpoints")
if os.path.exists(resume_dir):
for f in os.listdir(resume_dir):
if not f.endswith('.state'):
continue
file_path = os.path.join(resume_dir, f)
pstate = CallbackConfigParser()
try:
pstate.read_file(file_path)
except (ParsingError, MissingSectionHeaderError):
logger.warning("Parsing channel torrent resume file %s failed, deleting", file_path)
os.unlink(file_path)
continue
if pstate and pstate.has_option('download_defaults', 'channel_download') and \
pstate.get('download_defaults', 'channel_download'):
try:
name = pstate.get('state', 'metainfo')['info']['name']
if name and len(name) != CHANNEL_DIR_NAME_LENGTH:
os.unlink(file_path)
except (TypeError, KeyError, ValueError):
logger.debug("Malfored .pstate file %s found during cleanup of non-compliant channel torrents.",
file_path)
"""
Sets config and log systems up.
"""
# ConfigParser.read won't raise an exception if read fails because of missing file
# so if app starts and no user settings file exists, we simply
# get an "empty" config
#
# if config file is invalid, we raise a ValueError with details
DYNAMIC_DATA.is_first_run = not Path(_CONFIG_FILE_PATH).is_file()
try:
_CONFIG_PARSER.read(_CONFIG_FILE_PATH)
except DuplicateOptionError as duplicate_error:
raise ValueError(duplicate_error)
except ParsingError as parsing_error:
raise ValueError(parsing_error)
_setup_logging()
# add our main config section if not already present (i.e. previous read failed)
if not _CONFIG_PARSER.has_section(_MAIN_SECTION_NAME):
_get_logger().debug('adding main section to config')
_CONFIG_PARSER.add_section(_MAIN_SECTION_NAME)
# cleanup unused options
for option in _CONFIG_PARSER.options(_MAIN_SECTION_NAME):
if option not in _DEFAULTS.keys():
_get_logger().debug("Removed obsolete config option : '%s'", option)
_CONFIG_PARSER.remove_option(_MAIN_SECTION_NAME, option)
# dump user config
_get_logger().debug("***************************************************************************")
@type usage: C{str}
@param sections: additional (non optional) config file sections
to parse
@type sections: C{list} of C{str}
"""
self.command = command[:-3] if command.endswith('.py') else command
self.sections = sections
self.prefix = prefix
self.config = {}
self.valid_options = []
self.config_parser = configparser.SafeConfigParser()
self._warned_old_gbp_conf = False
try:
self.parse_config_files()
except configparser.ParsingError as err:
raise GbpError(str(err) + "\nSee 'man gbp.conf' for the format.")
OptionParser.__init__(self, option_class=GbpOption,
prog="gbp %s" % self.command,
usage=usage, version='%s %s' % (self.command,
gbp_version))
def _read_current_state(self):
config = configparser.ConfigParser()
try:
config.read(self.config['FILE_STORAGE']['filename'])
except configparser.ParsingError as e:
logging.getLogger().error("Error parsing file storage: " + str(e))
# create data array
current_states = []
for window in self.config['WINDOWS']:
# process current states
try:
state = int(config['statectrl'][window['name']])
except KeyError:
state = 0
current_states.append(state)
return current_states