Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def __str__(self):
return _('{0} -> {1}',
format_dict(self._match),
format_dict(self._values))
self._log.debug(_('No matching keyfile rule for {}.', device))
return False
try:
with open(filename, 'rb') as f:
keyfile = f.read()
except IOError:
self._log.warn(_('keyfile for {0} not found: {1}', device, filename))
return False
self._log.debug(_('unlocking {0} using keyfile {1}', device, filename))
try:
await device.unlock_keyfile(keyfile)
except Exception:
self._log.debug(_('failed to unlock {0} using keyfile', device))
self._log.debug(format_exc())
return False
self._log.info(_('unlocked {0} using keyfile', device))
return True
cache = udiskie.cache.PasswordCache(timeout)
except ImportError:
cache = None
self.mounter = udiskie.mount.Mounter(
config=config.device_config,
prompt=prompt,
browser=browser,
terminal=terminal,
cache=cache,
cache_hint=options['password_cache'],
udisks=self.udisks)
# check component availability
if options['notify'] and not has_Notify():
libnotify_not_available = _(
"Typelib for 'libnotify' is not available. Possible causes include:"
"\n\t- libnotify is not installed"
"\n\t- the typelib is provided by a separate package"
"\n\t- libnotify was built with introspection disabled"
"\n\nStarting udiskie without notifications.")
logging.getLogger(__name__).error(libnotify_not_available)
options['notify'] = False
show_tray = options['tray'] or options['appindicator']
if show_tray and not _in_X:
no_X_session = _(
"Not run within X session. "
"\nStarting udiskie without tray icon.\n")
logging.getLogger(__name__).error(no_X_session)
show_tray = False
async def _unlock_from_keyfile(self, device):
if not self.udisks.keyfile_support:
return False
filename = match_config(self._config, device, 'keyfile', None)
if filename is None:
self._log.debug(_('No matching keyfile rule for {}.', device))
return False
try:
with open(filename, 'rb') as f:
keyfile = f.read()
except IOError:
self._log.warn(_('keyfile for {0} not found: {1}', device, filename))
return False
self._log.debug(_('unlocking {0} using keyfile {1}', device, filename))
try:
await device.unlock_keyfile(keyfile)
except Exception:
self._log.debug(_('failed to unlock {0} using keyfile', device))
self._log.debug(format_exc())
return False
self._log.info(_('unlocked {0} using keyfile', device))
return True
# data structs containing the menu hierarchy:
Device = namedtuple('Device', ['root', 'branches', 'device', 'label', 'methods'])
Action = namedtuple('Action', ['method', 'device', 'label', 'action'])
class DeviceActions:
_labels = {
'browse': _('Browse {0}'),
'terminal': _('Hack on {0}'),
'mount': _('Mount {0}'),
'unmount': _('Unmount {0}'),
'unlock': _('Unlock {0}'),
'lock': _('Lock {0}'),
'eject': _('Eject {1}'),
'detach': _('Unpower {1}'),
'forget_password': _('Clear password for {0}'),
'delete': _('Detach {0}'),
}
def __init__(self, mounter, actions={}):
self._mounter = mounter
self._actions = _actions = actions.copy()
setdefault(_actions, {
'browse': mounter.browse,
'terminal': mounter.terminal,
'mount': mounter.mount,
'unmount': mounter.unmount,
'unlock': mounter.unlock,
'lock': partial(mounter.remove, force=True),
'eject': partial(mounter.eject, force=True),
"""
Read YAML config file. Returns Config object.
:raises IOError: if the path does not exist
"""
# None => use default
if path is None:
for path in cls.default_pathes():
try:
return cls.from_file(path)
except IOError as e:
logging.getLogger(__name__).debug(
_("Failed to read config file: {0}", exc_message(e)))
except ImportError as e:
logging.getLogger(__name__).warn(
_("Failed to read {0!r}: {1}", path, exc_message(e)))
return cls({})
# False/'' => no config
if not path:
return cls({})
if os.path.splitext(path)[1].lower() == '.json':
from json import load
else:
from yaml import safe_load as load
with open(path) as f:
return cls(load(f))
return
# NOTE: The here used heuristic is prone to raise conditions.
if job_in_progress:
# Cache the action name for later use:
self._jobs[object_path] = action
else:
del self._jobs[object_path]
device = yield self._get_updated_device(object_path)
if self._check_action_success[action](device):
event = self._event_by_action[action]
self.trigger(event, device)
else:
# get and delete message, if available:
message = self._errors[action].pop(object_path, "")
self.trigger('job_failed', device, action, message)
self._log.info(_('{0} operation failed for device: {1}',
action, object_path))
def device_removed(self, device):
"""Show removal notification for specified device object."""
if not self._mounter.is_handleable(device):
return
device_file = device.device_presentation
if (device.is_drive or device.is_toplevel) and device_file:
self._show_notification(
'device_removed',
_('Device removed'),
_('device disappeared on {0.device_presentation}', device),
device.icon_name)
- implement :meth:`_init`
- provide a docstring
- extend :cvar:`option_defaults` and :cvar:`option_rules`.
"""
option_defaults = {
'log_level': logging.INFO,
}
option_rules = {
'log_level': Choice({
'--verbose': logging.DEBUG,
'--quiet': logging.ERROR}),
}
usage_remarks = _("""
Note, that the options in the individual groups are mutually exclusive.
The config file can be a JSON or preferably a YAML file. For an
example, see the MAN page (or doc/udiskie.8.txt in the repository).
""")
def __init__(self, argv=None):
"""Parse command line options, read config and initialize members."""
# parse program options (retrieve log level and config file name):
args = docopt(self.usage, version='udiskie ' + self.version)
default_opts = self.option_defaults
program_opts = self.program_options(args)
# initialize logging configuration:
log_level = program_opts.get('log_level', default_opts['log_level'])
debug = log_level <= logging.DEBUG
logging.config.dictConfig({
async def _unlock_from_keyfile(self, device):
if not self.udisks.keyfile_support:
return False
filename = match_config(self._config, device, 'keyfile', None)
if filename is None:
self._log.debug(_('No matching keyfile rule for {}.', device))
return False
try:
with open(filename, 'rb') as f:
keyfile = f.read()
except IOError:
self._log.warn(_('keyfile for {0} not found: {1}', device, filename))
return False
self._log.debug(_('unlocking {0} using keyfile {1}', device, filename))
try:
await device.unlock_keyfile(keyfile)
except Exception:
self._log.debug(_('failed to unlock {0} using keyfile', device))
self._log.debug(format_exc())
return False
self._log.info(_('unlocked {0} using keyfile', device))
return True