repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
coldfix/udiskie | udiskie/notify.py | Notify.device_removed | 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) | python | 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) | [
"def",
"device_removed",
"(",
"self",
",",
"device",
")",
":",
"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",
")"
] | Show removal notification for specified device object. | [
"Show",
"removal",
"notification",
"for",
"specified",
"device",
"object",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L146-L156 | train |
coldfix/udiskie | udiskie/notify.py | Notify.job_failed | def job_failed(self, device, action, message):
"""Show 'Job failed' notification with 'Retry' button."""
if not self._mounter.is_handleable(device):
return
device_file = device.device_presentation or device.object_path
if message:
text = _('failed to {0} {1}:\n{2}', action, device_file, message)
else:
text = _('failed to {0} device {1}.', action, device_file)
try:
retry = getattr(self._mounter, action)
except AttributeError:
retry_action = None
else:
retry_action = ('retry', _('Retry'), retry, device)
self._show_notification(
'job_failed',
_('Job failed'), text,
device.icon_name,
retry_action) | python | def job_failed(self, device, action, message):
"""Show 'Job failed' notification with 'Retry' button."""
if not self._mounter.is_handleable(device):
return
device_file = device.device_presentation or device.object_path
if message:
text = _('failed to {0} {1}:\n{2}', action, device_file, message)
else:
text = _('failed to {0} device {1}.', action, device_file)
try:
retry = getattr(self._mounter, action)
except AttributeError:
retry_action = None
else:
retry_action = ('retry', _('Retry'), retry, device)
self._show_notification(
'job_failed',
_('Job failed'), text,
device.icon_name,
retry_action) | [
"def",
"job_failed",
"(",
"self",
",",
"device",
",",
"action",
",",
"message",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"device_file",
"=",
"device",
".",
"device_presentation",
"or",
"device",
".",
"object_path",
"if",
"message",
":",
"text",
"=",
"_",
"(",
"'failed to {0} {1}:\\n{2}'",
",",
"action",
",",
"device_file",
",",
"message",
")",
"else",
":",
"text",
"=",
"_",
"(",
"'failed to {0} device {1}.'",
",",
"action",
",",
"device_file",
")",
"try",
":",
"retry",
"=",
"getattr",
"(",
"self",
".",
"_mounter",
",",
"action",
")",
"except",
"AttributeError",
":",
"retry_action",
"=",
"None",
"else",
":",
"retry_action",
"=",
"(",
"'retry'",
",",
"_",
"(",
"'Retry'",
")",
",",
"retry",
",",
"device",
")",
"self",
".",
"_show_notification",
"(",
"'job_failed'",
",",
"_",
"(",
"'Job failed'",
")",
",",
"text",
",",
"device",
".",
"icon_name",
",",
"retry_action",
")"
] | Show 'Job failed' notification with 'Retry' button. | [
"Show",
"Job",
"failed",
"notification",
"with",
"Retry",
"button",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L158-L177 | train |
coldfix/udiskie | udiskie/notify.py | Notify._show_notification | def _show_notification(self,
event, summary, message, icon,
*actions):
"""
Show a notification.
:param str event: event name
:param str summary: notification title
:param str message: notification body
:param str icon: icon name
:param actions: each item is a tuple with parameters for _add_action
"""
notification = self._notify(summary, message, icon)
timeout = self._get_timeout(event)
if timeout != -1:
notification.set_timeout(int(timeout * 1000))
for action in actions:
if action and self._action_enabled(event, action[0]):
self._add_action(notification, *action)
try:
notification.show()
except GLib.GError as exc:
# Catch and log the exception. Starting udiskie with notifications
# enabled while not having a notification service installed is a
# mistake too easy to be made, but it shoud not render the rest of
# udiskie's logic useless by raising an exception before the
# automount handler gets invoked.
self._log.error(_("Failed to show notification: {0}", exc_message(exc)))
self._log.debug(format_exc()) | python | def _show_notification(self,
event, summary, message, icon,
*actions):
"""
Show a notification.
:param str event: event name
:param str summary: notification title
:param str message: notification body
:param str icon: icon name
:param actions: each item is a tuple with parameters for _add_action
"""
notification = self._notify(summary, message, icon)
timeout = self._get_timeout(event)
if timeout != -1:
notification.set_timeout(int(timeout * 1000))
for action in actions:
if action and self._action_enabled(event, action[0]):
self._add_action(notification, *action)
try:
notification.show()
except GLib.GError as exc:
# Catch and log the exception. Starting udiskie with notifications
# enabled while not having a notification service installed is a
# mistake too easy to be made, but it shoud not render the rest of
# udiskie's logic useless by raising an exception before the
# automount handler gets invoked.
self._log.error(_("Failed to show notification: {0}", exc_message(exc)))
self._log.debug(format_exc()) | [
"def",
"_show_notification",
"(",
"self",
",",
"event",
",",
"summary",
",",
"message",
",",
"icon",
",",
"*",
"actions",
")",
":",
"notification",
"=",
"self",
".",
"_notify",
"(",
"summary",
",",
"message",
",",
"icon",
")",
"timeout",
"=",
"self",
".",
"_get_timeout",
"(",
"event",
")",
"if",
"timeout",
"!=",
"-",
"1",
":",
"notification",
".",
"set_timeout",
"(",
"int",
"(",
"timeout",
"*",
"1000",
")",
")",
"for",
"action",
"in",
"actions",
":",
"if",
"action",
"and",
"self",
".",
"_action_enabled",
"(",
"event",
",",
"action",
"[",
"0",
"]",
")",
":",
"self",
".",
"_add_action",
"(",
"notification",
",",
"*",
"action",
")",
"try",
":",
"notification",
".",
"show",
"(",
")",
"except",
"GLib",
".",
"GError",
"as",
"exc",
":",
"# Catch and log the exception. Starting udiskie with notifications",
"# enabled while not having a notification service installed is a",
"# mistake too easy to be made, but it shoud not render the rest of",
"# udiskie's logic useless by raising an exception before the",
"# automount handler gets invoked.",
"self",
".",
"_log",
".",
"error",
"(",
"_",
"(",
"\"Failed to show notification: {0}\"",
",",
"exc_message",
"(",
"exc",
")",
")",
")",
"self",
".",
"_log",
".",
"debug",
"(",
"format_exc",
"(",
")",
")"
] | Show a notification.
:param str event: event name
:param str summary: notification title
:param str message: notification body
:param str icon: icon name
:param actions: each item is a tuple with parameters for _add_action | [
"Show",
"a",
"notification",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L179-L207 | train |
coldfix/udiskie | udiskie/notify.py | Notify._add_action | def _add_action(self, notification, action, label, callback, *args):
"""
Show an action button button in mount notifications.
Note, this only works with some libnotify services.
"""
on_action_click = run_bg(lambda *_: callback(*args))
try:
# this is the correct signature for Notify-0.7, the last argument
# being 'user_data':
notification.add_action(action, label, on_action_click, None)
except TypeError:
# this is the signature for some older version, I don't know what
# the last argument is for.
notification.add_action(action, label, on_action_click, None, None)
# gi.Notify does not store hard references to the notification
# objects. When a signal is received and the notification does not
# exist anymore, no handler will be called. Therefore, we need to
# prevent these notifications from being destroyed by storing
# references:
notification.connect('closed', self._notifications.remove)
self._notifications.append(notification) | python | def _add_action(self, notification, action, label, callback, *args):
"""
Show an action button button in mount notifications.
Note, this only works with some libnotify services.
"""
on_action_click = run_bg(lambda *_: callback(*args))
try:
# this is the correct signature for Notify-0.7, the last argument
# being 'user_data':
notification.add_action(action, label, on_action_click, None)
except TypeError:
# this is the signature for some older version, I don't know what
# the last argument is for.
notification.add_action(action, label, on_action_click, None, None)
# gi.Notify does not store hard references to the notification
# objects. When a signal is received and the notification does not
# exist anymore, no handler will be called. Therefore, we need to
# prevent these notifications from being destroyed by storing
# references:
notification.connect('closed', self._notifications.remove)
self._notifications.append(notification) | [
"def",
"_add_action",
"(",
"self",
",",
"notification",
",",
"action",
",",
"label",
",",
"callback",
",",
"*",
"args",
")",
":",
"on_action_click",
"=",
"run_bg",
"(",
"lambda",
"*",
"_",
":",
"callback",
"(",
"*",
"args",
")",
")",
"try",
":",
"# this is the correct signature for Notify-0.7, the last argument",
"# being 'user_data':",
"notification",
".",
"add_action",
"(",
"action",
",",
"label",
",",
"on_action_click",
",",
"None",
")",
"except",
"TypeError",
":",
"# this is the signature for some older version, I don't know what",
"# the last argument is for.",
"notification",
".",
"add_action",
"(",
"action",
",",
"label",
",",
"on_action_click",
",",
"None",
",",
"None",
")",
"# gi.Notify does not store hard references to the notification",
"# objects. When a signal is received and the notification does not",
"# exist anymore, no handler will be called. Therefore, we need to",
"# prevent these notifications from being destroyed by storing",
"# references:",
"notification",
".",
"connect",
"(",
"'closed'",
",",
"self",
".",
"_notifications",
".",
"remove",
")",
"self",
".",
"_notifications",
".",
"append",
"(",
"notification",
")"
] | Show an action button button in mount notifications.
Note, this only works with some libnotify services. | [
"Show",
"an",
"action",
"button",
"button",
"in",
"mount",
"notifications",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L209-L230 | train |
coldfix/udiskie | udiskie/notify.py | Notify._action_enabled | def _action_enabled(self, event, action):
"""Check if an action for a notification is enabled."""
event_actions = self._aconfig.get(event)
if event_actions is None:
return True
if event_actions is False:
return False
return action in event_actions | python | def _action_enabled(self, event, action):
"""Check if an action for a notification is enabled."""
event_actions = self._aconfig.get(event)
if event_actions is None:
return True
if event_actions is False:
return False
return action in event_actions | [
"def",
"_action_enabled",
"(",
"self",
",",
"event",
",",
"action",
")",
":",
"event_actions",
"=",
"self",
".",
"_aconfig",
".",
"get",
"(",
"event",
")",
"if",
"event_actions",
"is",
"None",
":",
"return",
"True",
"if",
"event_actions",
"is",
"False",
":",
"return",
"False",
"return",
"action",
"in",
"event_actions"
] | Check if an action for a notification is enabled. | [
"Check",
"if",
"an",
"action",
"for",
"a",
"notification",
"is",
"enabled",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L240-L247 | train |
coldfix/udiskie | udiskie/notify.py | Notify._has_actions | def _has_actions(self, event):
"""Check if a notification type has any enabled actions."""
event_actions = self._aconfig.get(event)
return event_actions is None or bool(event_actions) | python | def _has_actions(self, event):
"""Check if a notification type has any enabled actions."""
event_actions = self._aconfig.get(event)
return event_actions is None or bool(event_actions) | [
"def",
"_has_actions",
"(",
"self",
",",
"event",
")",
":",
"event_actions",
"=",
"self",
".",
"_aconfig",
".",
"get",
"(",
"event",
")",
"return",
"event_actions",
"is",
"None",
"or",
"bool",
"(",
"event_actions",
")"
] | Check if a notification type has any enabled actions. | [
"Check",
"if",
"a",
"notification",
"type",
"has",
"any",
"enabled",
"actions",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L249-L252 | train |
coldfix/udiskie | udiskie/config.py | DeviceFilter.match | def match(self, device):
"""Check if the device object matches this filter."""
return all(match_value(getattr(device, k), v)
for k, v in self._match.items()) | python | def match(self, device):
"""Check if the device object matches this filter."""
return all(match_value(getattr(device, k), v)
for k, v in self._match.items()) | [
"def",
"match",
"(",
"self",
",",
"device",
")",
":",
"return",
"all",
"(",
"match_value",
"(",
"getattr",
"(",
"device",
",",
"k",
")",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_match",
".",
"items",
"(",
")",
")"
] | Check if the device object matches this filter. | [
"Check",
"if",
"the",
"device",
"object",
"matches",
"this",
"filter",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/config.py#L118-L121 | train |
coldfix/udiskie | udiskie/config.py | DeviceFilter.value | def value(self, kind, device):
"""
Get the value for the device object associated with this filter.
If :meth:`match` is False for the device, the return value of this
method is undefined.
"""
self._log.debug(_('{0}(match={1!r}, {2}={3!r}) used for {4}',
self.__class__.__name__,
self._match,
kind, self._values[kind],
device.object_path))
return self._values[kind] | python | def value(self, kind, device):
"""
Get the value for the device object associated with this filter.
If :meth:`match` is False for the device, the return value of this
method is undefined.
"""
self._log.debug(_('{0}(match={1!r}, {2}={3!r}) used for {4}',
self.__class__.__name__,
self._match,
kind, self._values[kind],
device.object_path))
return self._values[kind] | [
"def",
"value",
"(",
"self",
",",
"kind",
",",
"device",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'{0}(match={1!r}, {2}={3!r}) used for {4}'",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"_match",
",",
"kind",
",",
"self",
".",
"_values",
"[",
"kind",
"]",
",",
"device",
".",
"object_path",
")",
")",
"return",
"self",
".",
"_values",
"[",
"kind",
"]"
] | Get the value for the device object associated with this filter.
If :meth:`match` is False for the device, the return value of this
method is undefined. | [
"Get",
"the",
"value",
"for",
"the",
"device",
"object",
"associated",
"with",
"this",
"filter",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/config.py#L126-L138 | train |
coldfix/udiskie | udiskie/config.py | Config.default_pathes | def default_pathes(cls):
"""Return the default config file pathes as a list."""
try:
from xdg.BaseDirectory import xdg_config_home as config_home
except ImportError:
config_home = os.path.expanduser('~/.config')
return [os.path.join(config_home, 'udiskie', 'config.yml'),
os.path.join(config_home, 'udiskie', 'config.json')] | python | def default_pathes(cls):
"""Return the default config file pathes as a list."""
try:
from xdg.BaseDirectory import xdg_config_home as config_home
except ImportError:
config_home = os.path.expanduser('~/.config')
return [os.path.join(config_home, 'udiskie', 'config.yml'),
os.path.join(config_home, 'udiskie', 'config.json')] | [
"def",
"default_pathes",
"(",
"cls",
")",
":",
"try",
":",
"from",
"xdg",
".",
"BaseDirectory",
"import",
"xdg_config_home",
"as",
"config_home",
"except",
"ImportError",
":",
"config_home",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.config'",
")",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"config_home",
",",
"'udiskie'",
",",
"'config.yml'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"config_home",
",",
"'udiskie'",
",",
"'config.json'",
")",
"]"
] | Return the default config file pathes as a list. | [
"Return",
"the",
"default",
"config",
"file",
"pathes",
"as",
"a",
"list",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/config.py#L186-L193 | train |
coldfix/udiskie | udiskie/config.py | Config.from_file | def from_file(cls, path=None):
"""
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)) | python | def from_file(cls, path=None):
"""
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)) | [
"def",
"from_file",
"(",
"cls",
",",
"path",
"=",
"None",
")",
":",
"# 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",
")",
")"
] | Read YAML config file. Returns Config object.
:raises IOError: if the path does not exist | [
"Read",
"YAML",
"config",
"file",
".",
"Returns",
"Config",
"object",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/config.py#L196-L222 | train |
coldfix/udiskie | udiskie/tray.py | Icons.get_icon_name | def get_icon_name(self, icon_id: str) -> str:
"""Lookup the system icon name from udisie-internal id."""
icon_theme = Gtk.IconTheme.get_default()
for name in self._icon_names[icon_id]:
if icon_theme.has_icon(name):
return name
return 'not-available' | python | def get_icon_name(self, icon_id: str) -> str:
"""Lookup the system icon name from udisie-internal id."""
icon_theme = Gtk.IconTheme.get_default()
for name in self._icon_names[icon_id]:
if icon_theme.has_icon(name):
return name
return 'not-available' | [
"def",
"get_icon_name",
"(",
"self",
",",
"icon_id",
":",
"str",
")",
"->",
"str",
":",
"icon_theme",
"=",
"Gtk",
".",
"IconTheme",
".",
"get_default",
"(",
")",
"for",
"name",
"in",
"self",
".",
"_icon_names",
"[",
"icon_id",
"]",
":",
"if",
"icon_theme",
".",
"has_icon",
"(",
"name",
")",
":",
"return",
"name",
"return",
"'not-available'"
] | Lookup the system icon name from udisie-internal id. | [
"Lookup",
"the",
"system",
"icon",
"name",
"from",
"udisie",
"-",
"internal",
"id",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L73-L79 | train |
coldfix/udiskie | udiskie/tray.py | Icons.get_icon | def get_icon(self, icon_id: str, size: "Gtk.IconSize") -> "Gtk.Image":
"""Load Gtk.Image from udiskie-internal id."""
return Gtk.Image.new_from_gicon(self.get_gicon(icon_id), size) | python | def get_icon(self, icon_id: str, size: "Gtk.IconSize") -> "Gtk.Image":
"""Load Gtk.Image from udiskie-internal id."""
return Gtk.Image.new_from_gicon(self.get_gicon(icon_id), size) | [
"def",
"get_icon",
"(",
"self",
",",
"icon_id",
":",
"str",
",",
"size",
":",
"\"Gtk.IconSize\"",
")",
"->",
"\"Gtk.Image\"",
":",
"return",
"Gtk",
".",
"Image",
".",
"new_from_gicon",
"(",
"self",
".",
"get_gicon",
"(",
"icon_id",
")",
",",
"size",
")"
] | Load Gtk.Image from udiskie-internal id. | [
"Load",
"Gtk",
".",
"Image",
"from",
"udiskie",
"-",
"internal",
"id",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L81-L83 | train |
coldfix/udiskie | udiskie/tray.py | Icons.get_gicon | def get_gicon(self, icon_id: str) -> "Gio.Icon":
"""Lookup Gio.Icon from udiskie-internal id."""
return Gio.ThemedIcon.new_from_names(self._icon_names[icon_id]) | python | def get_gicon(self, icon_id: str) -> "Gio.Icon":
"""Lookup Gio.Icon from udiskie-internal id."""
return Gio.ThemedIcon.new_from_names(self._icon_names[icon_id]) | [
"def",
"get_gicon",
"(",
"self",
",",
"icon_id",
":",
"str",
")",
"->",
"\"Gio.Icon\"",
":",
"return",
"Gio",
".",
"ThemedIcon",
".",
"new_from_names",
"(",
"self",
".",
"_icon_names",
"[",
"icon_id",
"]",
")"
] | Lookup Gio.Icon from udiskie-internal id. | [
"Lookup",
"Gio",
".",
"Icon",
"from",
"udiskie",
"-",
"internal",
"id",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L85-L87 | train |
coldfix/udiskie | udiskie/tray.py | UdiskieMenu._insert_options | def _insert_options(self, menu):
"""Add configuration options to menu."""
menu.append(Gtk.SeparatorMenuItem())
menu.append(self._menuitem(
_('Mount disc image'),
self._icons.get_icon('losetup', Gtk.IconSize.MENU),
run_bg(lambda _: self._losetup())
))
menu.append(Gtk.SeparatorMenuItem())
menu.append(self._menuitem(
_("Enable automounting"),
icon=None,
onclick=lambda _: self._daemon.automounter.toggle_on(),
checked=self._daemon.automounter.is_on(),
))
menu.append(self._menuitem(
_("Enable notifications"),
icon=None,
onclick=lambda _: self._daemon.notify.toggle(),
checked=self._daemon.notify.active,
))
# append menu item for closing the application
if self._quit_action:
menu.append(Gtk.SeparatorMenuItem())
menu.append(self._menuitem(
_('Quit'),
self._icons.get_icon('quit', Gtk.IconSize.MENU),
lambda _: self._quit_action()
)) | python | def _insert_options(self, menu):
"""Add configuration options to menu."""
menu.append(Gtk.SeparatorMenuItem())
menu.append(self._menuitem(
_('Mount disc image'),
self._icons.get_icon('losetup', Gtk.IconSize.MENU),
run_bg(lambda _: self._losetup())
))
menu.append(Gtk.SeparatorMenuItem())
menu.append(self._menuitem(
_("Enable automounting"),
icon=None,
onclick=lambda _: self._daemon.automounter.toggle_on(),
checked=self._daemon.automounter.is_on(),
))
menu.append(self._menuitem(
_("Enable notifications"),
icon=None,
onclick=lambda _: self._daemon.notify.toggle(),
checked=self._daemon.notify.active,
))
# append menu item for closing the application
if self._quit_action:
menu.append(Gtk.SeparatorMenuItem())
menu.append(self._menuitem(
_('Quit'),
self._icons.get_icon('quit', Gtk.IconSize.MENU),
lambda _: self._quit_action()
)) | [
"def",
"_insert_options",
"(",
"self",
",",
"menu",
")",
":",
"menu",
".",
"append",
"(",
"Gtk",
".",
"SeparatorMenuItem",
"(",
")",
")",
"menu",
".",
"append",
"(",
"self",
".",
"_menuitem",
"(",
"_",
"(",
"'Mount disc image'",
")",
",",
"self",
".",
"_icons",
".",
"get_icon",
"(",
"'losetup'",
",",
"Gtk",
".",
"IconSize",
".",
"MENU",
")",
",",
"run_bg",
"(",
"lambda",
"_",
":",
"self",
".",
"_losetup",
"(",
")",
")",
")",
")",
"menu",
".",
"append",
"(",
"Gtk",
".",
"SeparatorMenuItem",
"(",
")",
")",
"menu",
".",
"append",
"(",
"self",
".",
"_menuitem",
"(",
"_",
"(",
"\"Enable automounting\"",
")",
",",
"icon",
"=",
"None",
",",
"onclick",
"=",
"lambda",
"_",
":",
"self",
".",
"_daemon",
".",
"automounter",
".",
"toggle_on",
"(",
")",
",",
"checked",
"=",
"self",
".",
"_daemon",
".",
"automounter",
".",
"is_on",
"(",
")",
",",
")",
")",
"menu",
".",
"append",
"(",
"self",
".",
"_menuitem",
"(",
"_",
"(",
"\"Enable notifications\"",
")",
",",
"icon",
"=",
"None",
",",
"onclick",
"=",
"lambda",
"_",
":",
"self",
".",
"_daemon",
".",
"notify",
".",
"toggle",
"(",
")",
",",
"checked",
"=",
"self",
".",
"_daemon",
".",
"notify",
".",
"active",
",",
")",
")",
"# append menu item for closing the application",
"if",
"self",
".",
"_quit_action",
":",
"menu",
".",
"append",
"(",
"Gtk",
".",
"SeparatorMenuItem",
"(",
")",
")",
"menu",
".",
"append",
"(",
"self",
".",
"_menuitem",
"(",
"_",
"(",
"'Quit'",
")",
",",
"self",
".",
"_icons",
".",
"get_icon",
"(",
"'quit'",
",",
"Gtk",
".",
"IconSize",
".",
"MENU",
")",
",",
"lambda",
"_",
":",
"self",
".",
"_quit_action",
"(",
")",
")",
")"
] | Add configuration options to menu. | [
"Add",
"configuration",
"options",
"to",
"menu",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L155-L183 | train |
coldfix/udiskie | udiskie/tray.py | UdiskieMenu.detect | def detect(self):
"""Detect all currently known devices. Returns the root device."""
root = self._actions.detect()
prune_empty_node(root, set())
return root | python | def detect(self):
"""Detect all currently known devices. Returns the root device."""
root = self._actions.detect()
prune_empty_node(root, set())
return root | [
"def",
"detect",
"(",
"self",
")",
":",
"root",
"=",
"self",
".",
"_actions",
".",
"detect",
"(",
")",
"prune_empty_node",
"(",
"root",
",",
"set",
"(",
")",
")",
"return",
"root"
] | Detect all currently known devices. Returns the root device. | [
"Detect",
"all",
"currently",
"known",
"devices",
".",
"Returns",
"the",
"root",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L196-L200 | train |
coldfix/udiskie | udiskie/tray.py | UdiskieMenu._create_menu | def _create_menu(self, items):
"""
Create a menu from the given node.
:param list items: list of menu items
:returns: a new Gtk.Menu object holding all items of the node
"""
menu = Gtk.Menu()
self._create_menu_items(menu, items)
return menu | python | def _create_menu(self, items):
"""
Create a menu from the given node.
:param list items: list of menu items
:returns: a new Gtk.Menu object holding all items of the node
"""
menu = Gtk.Menu()
self._create_menu_items(menu, items)
return menu | [
"def",
"_create_menu",
"(",
"self",
",",
"items",
")",
":",
"menu",
"=",
"Gtk",
".",
"Menu",
"(",
")",
"self",
".",
"_create_menu_items",
"(",
"menu",
",",
"items",
")",
"return",
"menu"
] | Create a menu from the given node.
:param list items: list of menu items
:returns: a new Gtk.Menu object holding all items of the node | [
"Create",
"a",
"menu",
"from",
"the",
"given",
"node",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L202-L211 | train |
coldfix/udiskie | udiskie/tray.py | UdiskieMenu._menuitem | def _menuitem(self, label, icon, onclick, checked=None):
"""
Create a generic menu item.
:param str label: text
:param Gtk.Image icon: icon (may be ``None``)
:param onclick: onclick handler, either a callable or Gtk.Menu
:returns: the menu item object
:rtype: Gtk.MenuItem
"""
if checked is not None:
item = Gtk.CheckMenuItem()
item.set_active(checked)
elif icon is None:
item = Gtk.MenuItem()
else:
item = Gtk.ImageMenuItem()
item.set_image(icon)
# I don't really care for the "show icons only for nouns, not
# for verbs" policy:
item.set_always_show_image(True)
if label is not None:
item.set_label(label)
if isinstance(onclick, Gtk.Menu):
item.set_submenu(onclick)
elif onclick is not None:
item.connect('activate', onclick)
return item | python | def _menuitem(self, label, icon, onclick, checked=None):
"""
Create a generic menu item.
:param str label: text
:param Gtk.Image icon: icon (may be ``None``)
:param onclick: onclick handler, either a callable or Gtk.Menu
:returns: the menu item object
:rtype: Gtk.MenuItem
"""
if checked is not None:
item = Gtk.CheckMenuItem()
item.set_active(checked)
elif icon is None:
item = Gtk.MenuItem()
else:
item = Gtk.ImageMenuItem()
item.set_image(icon)
# I don't really care for the "show icons only for nouns, not
# for verbs" policy:
item.set_always_show_image(True)
if label is not None:
item.set_label(label)
if isinstance(onclick, Gtk.Menu):
item.set_submenu(onclick)
elif onclick is not None:
item.connect('activate', onclick)
return item | [
"def",
"_menuitem",
"(",
"self",
",",
"label",
",",
"icon",
",",
"onclick",
",",
"checked",
"=",
"None",
")",
":",
"if",
"checked",
"is",
"not",
"None",
":",
"item",
"=",
"Gtk",
".",
"CheckMenuItem",
"(",
")",
"item",
".",
"set_active",
"(",
"checked",
")",
"elif",
"icon",
"is",
"None",
":",
"item",
"=",
"Gtk",
".",
"MenuItem",
"(",
")",
"else",
":",
"item",
"=",
"Gtk",
".",
"ImageMenuItem",
"(",
")",
"item",
".",
"set_image",
"(",
"icon",
")",
"# I don't really care for the \"show icons only for nouns, not",
"# for verbs\" policy:",
"item",
".",
"set_always_show_image",
"(",
"True",
")",
"if",
"label",
"is",
"not",
"None",
":",
"item",
".",
"set_label",
"(",
"label",
")",
"if",
"isinstance",
"(",
"onclick",
",",
"Gtk",
".",
"Menu",
")",
":",
"item",
".",
"set_submenu",
"(",
"onclick",
")",
"elif",
"onclick",
"is",
"not",
"None",
":",
"item",
".",
"connect",
"(",
"'activate'",
",",
"onclick",
")",
"return",
"item"
] | Create a generic menu item.
:param str label: text
:param Gtk.Image icon: icon (may be ``None``)
:param onclick: onclick handler, either a callable or Gtk.Menu
:returns: the menu item object
:rtype: Gtk.MenuItem | [
"Create",
"a",
"generic",
"menu",
"item",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L245-L272 | train |
coldfix/udiskie | udiskie/tray.py | UdiskieMenu._prepare_menu | def _prepare_menu(self, node, flat=None):
"""
Prepare the menu hierarchy from the given device tree.
:param Device node: root node of device hierarchy
:returns: menu hierarchy as list
"""
if flat is None:
flat = self.flat
ItemGroup = MenuSection if flat else SubMenu
return [
ItemGroup(branch.label, self._collapse_device(branch, flat))
for branch in node.branches
if branch.methods or branch.branches
] | python | def _prepare_menu(self, node, flat=None):
"""
Prepare the menu hierarchy from the given device tree.
:param Device node: root node of device hierarchy
:returns: menu hierarchy as list
"""
if flat is None:
flat = self.flat
ItemGroup = MenuSection if flat else SubMenu
return [
ItemGroup(branch.label, self._collapse_device(branch, flat))
for branch in node.branches
if branch.methods or branch.branches
] | [
"def",
"_prepare_menu",
"(",
"self",
",",
"node",
",",
"flat",
"=",
"None",
")",
":",
"if",
"flat",
"is",
"None",
":",
"flat",
"=",
"self",
".",
"flat",
"ItemGroup",
"=",
"MenuSection",
"if",
"flat",
"else",
"SubMenu",
"return",
"[",
"ItemGroup",
"(",
"branch",
".",
"label",
",",
"self",
".",
"_collapse_device",
"(",
"branch",
",",
"flat",
")",
")",
"for",
"branch",
"in",
"node",
".",
"branches",
"if",
"branch",
".",
"methods",
"or",
"branch",
".",
"branches",
"]"
] | Prepare the menu hierarchy from the given device tree.
:param Device node: root node of device hierarchy
:returns: menu hierarchy as list | [
"Prepare",
"the",
"menu",
"hierarchy",
"from",
"the",
"given",
"device",
"tree",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L274-L288 | train |
coldfix/udiskie | udiskie/tray.py | UdiskieMenu._collapse_device | def _collapse_device(self, node, flat):
"""Collapse device hierarchy into a flat folder."""
items = [item
for branch in node.branches
for item in self._collapse_device(branch, flat)
if item]
show_all = not flat or self._quickmenu_actions == 'all'
methods = node.methods if show_all else [
method
for method in node.methods
if method.method in self._quickmenu_actions
]
if flat:
items.extend(methods)
else:
items.append(MenuSection(None, methods))
return items | python | def _collapse_device(self, node, flat):
"""Collapse device hierarchy into a flat folder."""
items = [item
for branch in node.branches
for item in self._collapse_device(branch, flat)
if item]
show_all = not flat or self._quickmenu_actions == 'all'
methods = node.methods if show_all else [
method
for method in node.methods
if method.method in self._quickmenu_actions
]
if flat:
items.extend(methods)
else:
items.append(MenuSection(None, methods))
return items | [
"def",
"_collapse_device",
"(",
"self",
",",
"node",
",",
"flat",
")",
":",
"items",
"=",
"[",
"item",
"for",
"branch",
"in",
"node",
".",
"branches",
"for",
"item",
"in",
"self",
".",
"_collapse_device",
"(",
"branch",
",",
"flat",
")",
"if",
"item",
"]",
"show_all",
"=",
"not",
"flat",
"or",
"self",
".",
"_quickmenu_actions",
"==",
"'all'",
"methods",
"=",
"node",
".",
"methods",
"if",
"show_all",
"else",
"[",
"method",
"for",
"method",
"in",
"node",
".",
"methods",
"if",
"method",
".",
"method",
"in",
"self",
".",
"_quickmenu_actions",
"]",
"if",
"flat",
":",
"items",
".",
"extend",
"(",
"methods",
")",
"else",
":",
"items",
".",
"append",
"(",
"MenuSection",
"(",
"None",
",",
"methods",
")",
")",
"return",
"items"
] | Collapse device hierarchy into a flat folder. | [
"Collapse",
"device",
"hierarchy",
"into",
"a",
"flat",
"folder",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L290-L306 | train |
coldfix/udiskie | udiskie/tray.py | TrayIcon._create_statusicon | def _create_statusicon(self):
"""Return a new Gtk.StatusIcon."""
statusicon = Gtk.StatusIcon()
statusicon.set_from_gicon(self._icons.get_gicon('media'))
statusicon.set_tooltip_text(_("udiskie"))
return statusicon | python | def _create_statusicon(self):
"""Return a new Gtk.StatusIcon."""
statusicon = Gtk.StatusIcon()
statusicon.set_from_gicon(self._icons.get_gicon('media'))
statusicon.set_tooltip_text(_("udiskie"))
return statusicon | [
"def",
"_create_statusicon",
"(",
"self",
")",
":",
"statusicon",
"=",
"Gtk",
".",
"StatusIcon",
"(",
")",
"statusicon",
".",
"set_from_gicon",
"(",
"self",
".",
"_icons",
".",
"get_gicon",
"(",
"'media'",
")",
")",
"statusicon",
".",
"set_tooltip_text",
"(",
"_",
"(",
"\"udiskie\"",
")",
")",
"return",
"statusicon"
] | Return a new Gtk.StatusIcon. | [
"Return",
"a",
"new",
"Gtk",
".",
"StatusIcon",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L337-L342 | train |
coldfix/udiskie | udiskie/tray.py | TrayIcon.show | def show(self, show=True):
"""Show or hide the tray icon."""
if show and not self.visible:
self._show()
if not show and self.visible:
self._hide() | python | def show(self, show=True):
"""Show or hide the tray icon."""
if show and not self.visible:
self._show()
if not show and self.visible:
self._hide() | [
"def",
"show",
"(",
"self",
",",
"show",
"=",
"True",
")",
":",
"if",
"show",
"and",
"not",
"self",
".",
"visible",
":",
"self",
".",
"_show",
"(",
")",
"if",
"not",
"show",
"and",
"self",
".",
"visible",
":",
"self",
".",
"_hide",
"(",
")"
] | Show or hide the tray icon. | [
"Show",
"or",
"hide",
"the",
"tray",
"icon",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L349-L354 | train |
coldfix/udiskie | udiskie/tray.py | TrayIcon._show | def _show(self):
"""Show the tray icon."""
if not self._icon:
self._icon = self._create_statusicon()
widget = self._icon
widget.set_visible(True)
self._conn_left = widget.connect("activate", self._activate)
self._conn_right = widget.connect("popup-menu", self._popup_menu) | python | def _show(self):
"""Show the tray icon."""
if not self._icon:
self._icon = self._create_statusicon()
widget = self._icon
widget.set_visible(True)
self._conn_left = widget.connect("activate", self._activate)
self._conn_right = widget.connect("popup-menu", self._popup_menu) | [
"def",
"_show",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_icon",
":",
"self",
".",
"_icon",
"=",
"self",
".",
"_create_statusicon",
"(",
")",
"widget",
"=",
"self",
".",
"_icon",
"widget",
".",
"set_visible",
"(",
"True",
")",
"self",
".",
"_conn_left",
"=",
"widget",
".",
"connect",
"(",
"\"activate\"",
",",
"self",
".",
"_activate",
")",
"self",
".",
"_conn_right",
"=",
"widget",
".",
"connect",
"(",
"\"popup-menu\"",
",",
"self",
".",
"_popup_menu",
")"
] | Show the tray icon. | [
"Show",
"the",
"tray",
"icon",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L356-L363 | train |
coldfix/udiskie | udiskie/tray.py | TrayIcon._hide | def _hide(self):
"""Hide the tray icon."""
self._icon.set_visible(False)
self._icon.disconnect(self._conn_left)
self._icon.disconnect(self._conn_right)
self._conn_left = None
self._conn_right = None | python | def _hide(self):
"""Hide the tray icon."""
self._icon.set_visible(False)
self._icon.disconnect(self._conn_left)
self._icon.disconnect(self._conn_right)
self._conn_left = None
self._conn_right = None | [
"def",
"_hide",
"(",
"self",
")",
":",
"self",
".",
"_icon",
".",
"set_visible",
"(",
"False",
")",
"self",
".",
"_icon",
".",
"disconnect",
"(",
"self",
".",
"_conn_left",
")",
"self",
".",
"_icon",
".",
"disconnect",
"(",
"self",
".",
"_conn_right",
")",
"self",
".",
"_conn_left",
"=",
"None",
"self",
".",
"_conn_right",
"=",
"None"
] | Hide the tray icon. | [
"Hide",
"the",
"tray",
"icon",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L365-L371 | train |
coldfix/udiskie | udiskie/tray.py | TrayIcon.create_context_menu | def create_context_menu(self, extended):
"""Create the context menu."""
menu = Gtk.Menu()
self._menu(menu, extended)
return menu | python | def create_context_menu(self, extended):
"""Create the context menu."""
menu = Gtk.Menu()
self._menu(menu, extended)
return menu | [
"def",
"create_context_menu",
"(",
"self",
",",
"extended",
")",
":",
"menu",
"=",
"Gtk",
".",
"Menu",
"(",
")",
"self",
".",
"_menu",
"(",
"menu",
",",
"extended",
")",
"return",
"menu"
] | Create the context menu. | [
"Create",
"the",
"context",
"menu",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L373-L377 | train |
coldfix/udiskie | udiskie/prompt.py | password_dialog | async def password_dialog(key, title, message, options):
"""
Show a Gtk password dialog.
:returns: the password or ``None`` if the user aborted the operation
:raises RuntimeError: if Gtk can not be properly initialized
"""
with PasswordDialog.create(key, title, message, options) as dialog:
response = await dialog
if response == Gtk.ResponseType.OK:
return PasswordResult(dialog.get_text(),
dialog.use_cache.get_active())
return None | python | async def password_dialog(key, title, message, options):
"""
Show a Gtk password dialog.
:returns: the password or ``None`` if the user aborted the operation
:raises RuntimeError: if Gtk can not be properly initialized
"""
with PasswordDialog.create(key, title, message, options) as dialog:
response = await dialog
if response == Gtk.ResponseType.OK:
return PasswordResult(dialog.get_text(),
dialog.use_cache.get_active())
return None | [
"async",
"def",
"password_dialog",
"(",
"key",
",",
"title",
",",
"message",
",",
"options",
")",
":",
"with",
"PasswordDialog",
".",
"create",
"(",
"key",
",",
"title",
",",
"message",
",",
"options",
")",
"as",
"dialog",
":",
"response",
"=",
"await",
"dialog",
"if",
"response",
"==",
"Gtk",
".",
"ResponseType",
".",
"OK",
":",
"return",
"PasswordResult",
"(",
"dialog",
".",
"get_text",
"(",
")",
",",
"dialog",
".",
"use_cache",
".",
"get_active",
"(",
")",
")",
"return",
"None"
] | Show a Gtk password dialog.
:returns: the password or ``None`` if the user aborted the operation
:raises RuntimeError: if Gtk can not be properly initialized | [
"Show",
"a",
"Gtk",
"password",
"dialog",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/prompt.py#L136-L148 | train |
coldfix/udiskie | udiskie/prompt.py | get_password_gui | def get_password_gui(device, options):
"""Get the password to unlock a device from GUI."""
text = _('Enter password for {0.device_presentation}: ', device)
try:
return password_dialog(device.id_uuid, 'udiskie', text, options)
except RuntimeError:
return None | python | def get_password_gui(device, options):
"""Get the password to unlock a device from GUI."""
text = _('Enter password for {0.device_presentation}: ', device)
try:
return password_dialog(device.id_uuid, 'udiskie', text, options)
except RuntimeError:
return None | [
"def",
"get_password_gui",
"(",
"device",
",",
"options",
")",
":",
"text",
"=",
"_",
"(",
"'Enter password for {0.device_presentation}: '",
",",
"device",
")",
"try",
":",
"return",
"password_dialog",
"(",
"device",
".",
"id_uuid",
",",
"'udiskie'",
",",
"text",
",",
"options",
")",
"except",
"RuntimeError",
":",
"return",
"None"
] | Get the password to unlock a device from GUI. | [
"Get",
"the",
"password",
"to",
"unlock",
"a",
"device",
"from",
"GUI",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/prompt.py#L151-L157 | train |
coldfix/udiskie | udiskie/prompt.py | get_password_tty | async def get_password_tty(device, options):
"""Get the password to unlock a device from terminal."""
# TODO: make this a TRUE async
text = _('Enter password for {0.device_presentation}: ', device)
try:
return getpass.getpass(text)
except EOFError:
print("")
return None | python | async def get_password_tty(device, options):
"""Get the password to unlock a device from terminal."""
# TODO: make this a TRUE async
text = _('Enter password for {0.device_presentation}: ', device)
try:
return getpass.getpass(text)
except EOFError:
print("")
return None | [
"async",
"def",
"get_password_tty",
"(",
"device",
",",
"options",
")",
":",
"# TODO: make this a TRUE async",
"text",
"=",
"_",
"(",
"'Enter password for {0.device_presentation}: '",
",",
"device",
")",
"try",
":",
"return",
"getpass",
".",
"getpass",
"(",
"text",
")",
"except",
"EOFError",
":",
"print",
"(",
"\"\"",
")",
"return",
"None"
] | Get the password to unlock a device from terminal. | [
"Get",
"the",
"password",
"to",
"unlock",
"a",
"device",
"from",
"terminal",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/prompt.py#L160-L168 | train |
coldfix/udiskie | udiskie/prompt.py | password | def password(password_command):
"""Create a password prompt function."""
gui = lambda: has_Gtk() and get_password_gui
tty = lambda: sys.stdin.isatty() and get_password_tty
if password_command == 'builtin:gui':
return gui() or tty()
elif password_command == 'builtin:tty':
return tty() or gui()
elif password_command:
return DeviceCommand(password_command).password
else:
return None | python | def password(password_command):
"""Create a password prompt function."""
gui = lambda: has_Gtk() and get_password_gui
tty = lambda: sys.stdin.isatty() and get_password_tty
if password_command == 'builtin:gui':
return gui() or tty()
elif password_command == 'builtin:tty':
return tty() or gui()
elif password_command:
return DeviceCommand(password_command).password
else:
return None | [
"def",
"password",
"(",
"password_command",
")",
":",
"gui",
"=",
"lambda",
":",
"has_Gtk",
"(",
")",
"and",
"get_password_gui",
"tty",
"=",
"lambda",
":",
"sys",
".",
"stdin",
".",
"isatty",
"(",
")",
"and",
"get_password_tty",
"if",
"password_command",
"==",
"'builtin:gui'",
":",
"return",
"gui",
"(",
")",
"or",
"tty",
"(",
")",
"elif",
"password_command",
"==",
"'builtin:tty'",
":",
"return",
"tty",
"(",
")",
"or",
"gui",
"(",
")",
"elif",
"password_command",
":",
"return",
"DeviceCommand",
"(",
"password_command",
")",
".",
"password",
"else",
":",
"return",
"None"
] | Create a password prompt function. | [
"Create",
"a",
"password",
"prompt",
"function",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/prompt.py#L219-L230 | train |
coldfix/udiskie | udiskie/prompt.py | browser | def browser(browser_name='xdg-open'):
"""Create a browse-directory function."""
if not browser_name:
return None
argv = shlex.split(browser_name)
executable = find_executable(argv[0])
if executable is None:
# Why not raise an exception? -I think it is more convenient (for
# end users) to have a reasonable default, without enforcing it.
logging.getLogger(__name__).warn(
_("Can't find file browser: {0!r}. "
"You may want to change the value for the '-f' option.",
browser_name))
return None
def browse(path):
return subprocess.Popen(argv + [path])
return browse | python | def browser(browser_name='xdg-open'):
"""Create a browse-directory function."""
if not browser_name:
return None
argv = shlex.split(browser_name)
executable = find_executable(argv[0])
if executable is None:
# Why not raise an exception? -I think it is more convenient (for
# end users) to have a reasonable default, without enforcing it.
logging.getLogger(__name__).warn(
_("Can't find file browser: {0!r}. "
"You may want to change the value for the '-f' option.",
browser_name))
return None
def browse(path):
return subprocess.Popen(argv + [path])
return browse | [
"def",
"browser",
"(",
"browser_name",
"=",
"'xdg-open'",
")",
":",
"if",
"not",
"browser_name",
":",
"return",
"None",
"argv",
"=",
"shlex",
".",
"split",
"(",
"browser_name",
")",
"executable",
"=",
"find_executable",
"(",
"argv",
"[",
"0",
"]",
")",
"if",
"executable",
"is",
"None",
":",
"# Why not raise an exception? -I think it is more convenient (for",
"# end users) to have a reasonable default, without enforcing it.",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"warn",
"(",
"_",
"(",
"\"Can't find file browser: {0!r}. \"",
"\"You may want to change the value for the '-f' option.\"",
",",
"browser_name",
")",
")",
"return",
"None",
"def",
"browse",
"(",
"path",
")",
":",
"return",
"subprocess",
".",
"Popen",
"(",
"argv",
"+",
"[",
"path",
"]",
")",
"return",
"browse"
] | Create a browse-directory function. | [
"Create",
"a",
"browse",
"-",
"directory",
"function",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/prompt.py#L233-L253 | train |
coldfix/udiskie | udiskie/prompt.py | notify_command | def notify_command(command_format, mounter):
"""
Command notification tool.
This works similar to Notify, but will issue command instead of showing
the notifications on the desktop. This can then be used to react to events
from shell scripts.
The command can contain modern pythonic format placeholders like:
{device_file}. The following placeholders are supported:
event, device_file, device_id, device_size, drive, drive_label, id_label,
id_type, id_usage, id_uuid, mount_path, root
:param str command_format: command to run when an event occurs.
:param mounter: Mounter object
"""
udisks = mounter.udisks
for event in ['device_mounted', 'device_unmounted',
'device_locked', 'device_unlocked',
'device_added', 'device_removed',
'job_failed']:
udisks.connect(event, run_bg(DeviceCommand(command_format, event=event))) | python | def notify_command(command_format, mounter):
"""
Command notification tool.
This works similar to Notify, but will issue command instead of showing
the notifications on the desktop. This can then be used to react to events
from shell scripts.
The command can contain modern pythonic format placeholders like:
{device_file}. The following placeholders are supported:
event, device_file, device_id, device_size, drive, drive_label, id_label,
id_type, id_usage, id_uuid, mount_path, root
:param str command_format: command to run when an event occurs.
:param mounter: Mounter object
"""
udisks = mounter.udisks
for event in ['device_mounted', 'device_unmounted',
'device_locked', 'device_unlocked',
'device_added', 'device_removed',
'job_failed']:
udisks.connect(event, run_bg(DeviceCommand(command_format, event=event))) | [
"def",
"notify_command",
"(",
"command_format",
",",
"mounter",
")",
":",
"udisks",
"=",
"mounter",
".",
"udisks",
"for",
"event",
"in",
"[",
"'device_mounted'",
",",
"'device_unmounted'",
",",
"'device_locked'",
",",
"'device_unlocked'",
",",
"'device_added'",
",",
"'device_removed'",
",",
"'job_failed'",
"]",
":",
"udisks",
".",
"connect",
"(",
"event",
",",
"run_bg",
"(",
"DeviceCommand",
"(",
"command_format",
",",
"event",
"=",
"event",
")",
")",
")"
] | Command notification tool.
This works similar to Notify, but will issue command instead of showing
the notifications on the desktop. This can then be used to react to events
from shell scripts.
The command can contain modern pythonic format placeholders like:
{device_file}. The following placeholders are supported:
event, device_file, device_id, device_size, drive, drive_label, id_label,
id_type, id_usage, id_uuid, mount_path, root
:param str command_format: command to run when an event occurs.
:param mounter: Mounter object | [
"Command",
"notification",
"tool",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/prompt.py#L256-L277 | train |
coldfix/udiskie | udiskie/async_.py | exec_subprocess | async def exec_subprocess(argv):
"""
An Future task that represents a subprocess. If successful, the task's
result is set to the collected STDOUT of the subprocess.
:raises subprocess.CalledProcessError: if the subprocess returns a non-zero
exit code
"""
future = Future()
process = Gio.Subprocess.new(
argv,
Gio.SubprocessFlags.STDOUT_PIPE |
Gio.SubprocessFlags.STDIN_INHERIT)
stdin_buf = None
cancellable = None
process.communicate_utf8_async(
stdin_buf, cancellable, gio_callback, future)
result = await future
success, stdout, stderr = process.communicate_utf8_finish(result)
if not success:
raise RuntimeError("Subprocess did not exit normally!")
exit_code = process.get_exit_status()
if exit_code != 0:
raise CalledProcessError(
"Subprocess returned a non-zero exit-status!",
exit_code,
stdout)
return stdout | python | async def exec_subprocess(argv):
"""
An Future task that represents a subprocess. If successful, the task's
result is set to the collected STDOUT of the subprocess.
:raises subprocess.CalledProcessError: if the subprocess returns a non-zero
exit code
"""
future = Future()
process = Gio.Subprocess.new(
argv,
Gio.SubprocessFlags.STDOUT_PIPE |
Gio.SubprocessFlags.STDIN_INHERIT)
stdin_buf = None
cancellable = None
process.communicate_utf8_async(
stdin_buf, cancellable, gio_callback, future)
result = await future
success, stdout, stderr = process.communicate_utf8_finish(result)
if not success:
raise RuntimeError("Subprocess did not exit normally!")
exit_code = process.get_exit_status()
if exit_code != 0:
raise CalledProcessError(
"Subprocess returned a non-zero exit-status!",
exit_code,
stdout)
return stdout | [
"async",
"def",
"exec_subprocess",
"(",
"argv",
")",
":",
"future",
"=",
"Future",
"(",
")",
"process",
"=",
"Gio",
".",
"Subprocess",
".",
"new",
"(",
"argv",
",",
"Gio",
".",
"SubprocessFlags",
".",
"STDOUT_PIPE",
"|",
"Gio",
".",
"SubprocessFlags",
".",
"STDIN_INHERIT",
")",
"stdin_buf",
"=",
"None",
"cancellable",
"=",
"None",
"process",
".",
"communicate_utf8_async",
"(",
"stdin_buf",
",",
"cancellable",
",",
"gio_callback",
",",
"future",
")",
"result",
"=",
"await",
"future",
"success",
",",
"stdout",
",",
"stderr",
"=",
"process",
".",
"communicate_utf8_finish",
"(",
"result",
")",
"if",
"not",
"success",
":",
"raise",
"RuntimeError",
"(",
"\"Subprocess did not exit normally!\"",
")",
"exit_code",
"=",
"process",
".",
"get_exit_status",
"(",
")",
"if",
"exit_code",
"!=",
"0",
":",
"raise",
"CalledProcessError",
"(",
"\"Subprocess returned a non-zero exit-status!\"",
",",
"exit_code",
",",
"stdout",
")",
"return",
"stdout"
] | An Future task that represents a subprocess. If successful, the task's
result is set to the collected STDOUT of the subprocess.
:raises subprocess.CalledProcessError: if the subprocess returns a non-zero
exit code | [
"An",
"Future",
"task",
"that",
"represents",
"a",
"subprocess",
".",
"If",
"successful",
"the",
"task",
"s",
"result",
"is",
"set",
"to",
"the",
"collected",
"STDOUT",
"of",
"the",
"subprocess",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/async_.py#L206-L233 | train |
coldfix/udiskie | udiskie/async_.py | Future.set_exception | def set_exception(self, exception):
"""Signal unsuccessful completion."""
was_handled = self._finish(self.errbacks, exception)
if not was_handled:
traceback.print_exception(
type(exception), exception, exception.__traceback__) | python | def set_exception(self, exception):
"""Signal unsuccessful completion."""
was_handled = self._finish(self.errbacks, exception)
if not was_handled:
traceback.print_exception(
type(exception), exception, exception.__traceback__) | [
"def",
"set_exception",
"(",
"self",
",",
"exception",
")",
":",
"was_handled",
"=",
"self",
".",
"_finish",
"(",
"self",
".",
"errbacks",
",",
"exception",
")",
"if",
"not",
"was_handled",
":",
"traceback",
".",
"print_exception",
"(",
"type",
"(",
"exception",
")",
",",
"exception",
",",
"exception",
".",
"__traceback__",
")"
] | Signal unsuccessful completion. | [
"Signal",
"unsuccessful",
"completion",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/async_.py#L82-L87 | train |
coldfix/udiskie | udiskie/async_.py | gather._subtask_result | def _subtask_result(self, idx, value):
"""Receive a result from a single subtask."""
self._results[idx] = value
if len(self._results) == self._num_tasks:
self.set_result([
self._results[i]
for i in range(self._num_tasks)
]) | python | def _subtask_result(self, idx, value):
"""Receive a result from a single subtask."""
self._results[idx] = value
if len(self._results) == self._num_tasks:
self.set_result([
self._results[i]
for i in range(self._num_tasks)
]) | [
"def",
"_subtask_result",
"(",
"self",
",",
"idx",
",",
"value",
")",
":",
"self",
".",
"_results",
"[",
"idx",
"]",
"=",
"value",
"if",
"len",
"(",
"self",
".",
"_results",
")",
"==",
"self",
".",
"_num_tasks",
":",
"self",
".",
"set_result",
"(",
"[",
"self",
".",
"_results",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_num_tasks",
")",
"]",
")"
] | Receive a result from a single subtask. | [
"Receive",
"a",
"result",
"from",
"a",
"single",
"subtask",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/async_.py#L132-L139 | train |
coldfix/udiskie | udiskie/async_.py | gather._subtask_error | def _subtask_error(self, idx, error):
"""Receive an error from a single subtask."""
self.set_exception(error)
self.errbacks.clear() | python | def _subtask_error(self, idx, error):
"""Receive an error from a single subtask."""
self.set_exception(error)
self.errbacks.clear() | [
"def",
"_subtask_error",
"(",
"self",
",",
"idx",
",",
"error",
")",
":",
"self",
".",
"set_exception",
"(",
"error",
")",
"self",
".",
"errbacks",
".",
"clear",
"(",
")"
] | Receive an error from a single subtask. | [
"Receive",
"an",
"error",
"from",
"a",
"single",
"subtask",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/async_.py#L141-L144 | train |
coldfix/udiskie | udiskie/async_.py | Task._resume | def _resume(self, func, *args):
"""Resume the coroutine by throwing a value or returning a value from
the ``await`` and handle further awaits."""
try:
value = func(*args)
except StopIteration:
self._generator.close()
self.set_result(None)
except Exception as e:
self._generator.close()
self.set_exception(e)
else:
assert isinstance(value, Future)
value.callbacks.append(partial(self._resume, self._generator.send))
value.errbacks.append(partial(self._resume, self._generator.throw)) | python | def _resume(self, func, *args):
"""Resume the coroutine by throwing a value or returning a value from
the ``await`` and handle further awaits."""
try:
value = func(*args)
except StopIteration:
self._generator.close()
self.set_result(None)
except Exception as e:
self._generator.close()
self.set_exception(e)
else:
assert isinstance(value, Future)
value.callbacks.append(partial(self._resume, self._generator.send))
value.errbacks.append(partial(self._resume, self._generator.throw)) | [
"def",
"_resume",
"(",
"self",
",",
"func",
",",
"*",
"args",
")",
":",
"try",
":",
"value",
"=",
"func",
"(",
"*",
"args",
")",
"except",
"StopIteration",
":",
"self",
".",
"_generator",
".",
"close",
"(",
")",
"self",
".",
"set_result",
"(",
"None",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"_generator",
".",
"close",
"(",
")",
"self",
".",
"set_exception",
"(",
"e",
")",
"else",
":",
"assert",
"isinstance",
"(",
"value",
",",
"Future",
")",
"value",
".",
"callbacks",
".",
"append",
"(",
"partial",
"(",
"self",
".",
"_resume",
",",
"self",
".",
"_generator",
".",
"send",
")",
")",
"value",
".",
"errbacks",
".",
"append",
"(",
"partial",
"(",
"self",
".",
"_resume",
",",
"self",
".",
"_generator",
".",
"throw",
")",
")"
] | Resume the coroutine by throwing a value or returning a value from
the ``await`` and handle further awaits. | [
"Resume",
"the",
"coroutine",
"by",
"throwing",
"a",
"value",
"or",
"returning",
"a",
"value",
"from",
"the",
"await",
"and",
"handle",
"further",
"awaits",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/async_.py#L185-L199 | train |
relekang/python-semantic-release | semantic_release/history/parser_tag.py | parse_commit_message | def parse_commit_message(message: str) -> Tuple[int, str, Optional[str], Tuple[str, str, str]]:
"""
Parses a commit message according to the 1.0 version of python-semantic-release. It expects
a tag of some sort in the commit message and will use the rest of the first line as changelog
content.
:param message: A string of a commit message.
:raises UnknownCommitMessageStyleError: If it does not recognise the commit style
:return: A tuple of (level to bump, type of change, scope of change, a tuple with descriptions)
"""
parsed = re_parser.match(message)
if not parsed:
raise UnknownCommitMessageStyleError(
'Unable to parse the given commit message: {0}'.format(message)
)
subject = parsed.group('subject')
if config.get('semantic_release', 'minor_tag') in message:
level = 'feature'
level_bump = 2
if subject:
subject = subject.replace(config.get('semantic_release', 'minor_tag'.format(level)), '')
elif config.get('semantic_release', 'fix_tag') in message:
level = 'fix'
level_bump = 1
if subject:
subject = subject.replace(config.get('semantic_release', 'fix_tag'.format(level)), '')
else:
raise UnknownCommitMessageStyleError(
'Unable to parse the given commit message: {0}'.format(message)
)
if parsed.group('text') and 'BREAKING CHANGE' in parsed.group('text'):
level = 'breaking'
level_bump = 3
body, footer = parse_text_block(parsed.group('text'))
return level_bump, level, None, (subject.strip(), body.strip(), footer.strip()) | python | def parse_commit_message(message: str) -> Tuple[int, str, Optional[str], Tuple[str, str, str]]:
"""
Parses a commit message according to the 1.0 version of python-semantic-release. It expects
a tag of some sort in the commit message and will use the rest of the first line as changelog
content.
:param message: A string of a commit message.
:raises UnknownCommitMessageStyleError: If it does not recognise the commit style
:return: A tuple of (level to bump, type of change, scope of change, a tuple with descriptions)
"""
parsed = re_parser.match(message)
if not parsed:
raise UnknownCommitMessageStyleError(
'Unable to parse the given commit message: {0}'.format(message)
)
subject = parsed.group('subject')
if config.get('semantic_release', 'minor_tag') in message:
level = 'feature'
level_bump = 2
if subject:
subject = subject.replace(config.get('semantic_release', 'minor_tag'.format(level)), '')
elif config.get('semantic_release', 'fix_tag') in message:
level = 'fix'
level_bump = 1
if subject:
subject = subject.replace(config.get('semantic_release', 'fix_tag'.format(level)), '')
else:
raise UnknownCommitMessageStyleError(
'Unable to parse the given commit message: {0}'.format(message)
)
if parsed.group('text') and 'BREAKING CHANGE' in parsed.group('text'):
level = 'breaking'
level_bump = 3
body, footer = parse_text_block(parsed.group('text'))
return level_bump, level, None, (subject.strip(), body.strip(), footer.strip()) | [
"def",
"parse_commit_message",
"(",
"message",
":",
"str",
")",
"->",
"Tuple",
"[",
"int",
",",
"str",
",",
"Optional",
"[",
"str",
"]",
",",
"Tuple",
"[",
"str",
",",
"str",
",",
"str",
"]",
"]",
":",
"parsed",
"=",
"re_parser",
".",
"match",
"(",
"message",
")",
"if",
"not",
"parsed",
":",
"raise",
"UnknownCommitMessageStyleError",
"(",
"'Unable to parse the given commit message: {0}'",
".",
"format",
"(",
"message",
")",
")",
"subject",
"=",
"parsed",
".",
"group",
"(",
"'subject'",
")",
"if",
"config",
".",
"get",
"(",
"'semantic_release'",
",",
"'minor_tag'",
")",
"in",
"message",
":",
"level",
"=",
"'feature'",
"level_bump",
"=",
"2",
"if",
"subject",
":",
"subject",
"=",
"subject",
".",
"replace",
"(",
"config",
".",
"get",
"(",
"'semantic_release'",
",",
"'minor_tag'",
".",
"format",
"(",
"level",
")",
")",
",",
"''",
")",
"elif",
"config",
".",
"get",
"(",
"'semantic_release'",
",",
"'fix_tag'",
")",
"in",
"message",
":",
"level",
"=",
"'fix'",
"level_bump",
"=",
"1",
"if",
"subject",
":",
"subject",
"=",
"subject",
".",
"replace",
"(",
"config",
".",
"get",
"(",
"'semantic_release'",
",",
"'fix_tag'",
".",
"format",
"(",
"level",
")",
")",
",",
"''",
")",
"else",
":",
"raise",
"UnknownCommitMessageStyleError",
"(",
"'Unable to parse the given commit message: {0}'",
".",
"format",
"(",
"message",
")",
")",
"if",
"parsed",
".",
"group",
"(",
"'text'",
")",
"and",
"'BREAKING CHANGE'",
"in",
"parsed",
".",
"group",
"(",
"'text'",
")",
":",
"level",
"=",
"'breaking'",
"level_bump",
"=",
"3",
"body",
",",
"footer",
"=",
"parse_text_block",
"(",
"parsed",
".",
"group",
"(",
"'text'",
")",
")",
"return",
"level_bump",
",",
"level",
",",
"None",
",",
"(",
"subject",
".",
"strip",
"(",
")",
",",
"body",
".",
"strip",
"(",
")",
",",
"footer",
".",
"strip",
"(",
")",
")"
] | Parses a commit message according to the 1.0 version of python-semantic-release. It expects
a tag of some sort in the commit message and will use the rest of the first line as changelog
content.
:param message: A string of a commit message.
:raises UnknownCommitMessageStyleError: If it does not recognise the commit style
:return: A tuple of (level to bump, type of change, scope of change, a tuple with descriptions) | [
"Parses",
"a",
"commit",
"message",
"according",
"to",
"the",
"1",
".",
"0",
"version",
"of",
"python",
"-",
"semantic",
"-",
"release",
".",
"It",
"expects",
"a",
"tag",
"of",
"some",
"sort",
"in",
"the",
"commit",
"message",
"and",
"will",
"use",
"the",
"rest",
"of",
"the",
"first",
"line",
"as",
"changelog",
"content",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/parser_tag.py#L17-L60 | train |
relekang/python-semantic-release | semantic_release/ci_checks.py | checker | def checker(func: Callable) -> Callable:
"""
A decorator that will convert AssertionErrors into
CiVerificationError.
:param func: A function that will raise AssertionError
:return: The given function wrapped to raise a CiVerificationError on AssertionError
"""
def func_wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
return True
except AssertionError:
raise CiVerificationError(
'The verification check for the environment did not pass.'
)
return func_wrapper | python | def checker(func: Callable) -> Callable:
"""
A decorator that will convert AssertionErrors into
CiVerificationError.
:param func: A function that will raise AssertionError
:return: The given function wrapped to raise a CiVerificationError on AssertionError
"""
def func_wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
return True
except AssertionError:
raise CiVerificationError(
'The verification check for the environment did not pass.'
)
return func_wrapper | [
"def",
"checker",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"def",
"func_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"True",
"except",
"AssertionError",
":",
"raise",
"CiVerificationError",
"(",
"'The verification check for the environment did not pass.'",
")",
"return",
"func_wrapper"
] | A decorator that will convert AssertionErrors into
CiVerificationError.
:param func: A function that will raise AssertionError
:return: The given function wrapped to raise a CiVerificationError on AssertionError | [
"A",
"decorator",
"that",
"will",
"convert",
"AssertionErrors",
"into",
"CiVerificationError",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/ci_checks.py#L9-L27 | train |
relekang/python-semantic-release | semantic_release/ci_checks.py | travis | def travis(branch: str):
"""
Performs necessary checks to ensure that the travis build is one
that should create releases.
:param branch: The branch the environment should be running against.
"""
assert os.environ.get('TRAVIS_BRANCH') == branch
assert os.environ.get('TRAVIS_PULL_REQUEST') == 'false' | python | def travis(branch: str):
"""
Performs necessary checks to ensure that the travis build is one
that should create releases.
:param branch: The branch the environment should be running against.
"""
assert os.environ.get('TRAVIS_BRANCH') == branch
assert os.environ.get('TRAVIS_PULL_REQUEST') == 'false' | [
"def",
"travis",
"(",
"branch",
":",
"str",
")",
":",
"assert",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAVIS_BRANCH'",
")",
"==",
"branch",
"assert",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAVIS_PULL_REQUEST'",
")",
"==",
"'false'"
] | Performs necessary checks to ensure that the travis build is one
that should create releases.
:param branch: The branch the environment should be running against. | [
"Performs",
"necessary",
"checks",
"to",
"ensure",
"that",
"the",
"travis",
"build",
"is",
"one",
"that",
"should",
"create",
"releases",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/ci_checks.py#L31-L39 | train |
relekang/python-semantic-release | semantic_release/ci_checks.py | semaphore | def semaphore(branch: str):
"""
Performs necessary checks to ensure that the semaphore build is successful,
on the correct branch and not a pull-request.
:param branch: The branch the environment should be running against.
"""
assert os.environ.get('BRANCH_NAME') == branch
assert os.environ.get('PULL_REQUEST_NUMBER') is None
assert os.environ.get('SEMAPHORE_THREAD_RESULT') != 'failed' | python | def semaphore(branch: str):
"""
Performs necessary checks to ensure that the semaphore build is successful,
on the correct branch and not a pull-request.
:param branch: The branch the environment should be running against.
"""
assert os.environ.get('BRANCH_NAME') == branch
assert os.environ.get('PULL_REQUEST_NUMBER') is None
assert os.environ.get('SEMAPHORE_THREAD_RESULT') != 'failed' | [
"def",
"semaphore",
"(",
"branch",
":",
"str",
")",
":",
"assert",
"os",
".",
"environ",
".",
"get",
"(",
"'BRANCH_NAME'",
")",
"==",
"branch",
"assert",
"os",
".",
"environ",
".",
"get",
"(",
"'PULL_REQUEST_NUMBER'",
")",
"is",
"None",
"assert",
"os",
".",
"environ",
".",
"get",
"(",
"'SEMAPHORE_THREAD_RESULT'",
")",
"!=",
"'failed'"
] | Performs necessary checks to ensure that the semaphore build is successful,
on the correct branch and not a pull-request.
:param branch: The branch the environment should be running against. | [
"Performs",
"necessary",
"checks",
"to",
"ensure",
"that",
"the",
"semaphore",
"build",
"is",
"successful",
"on",
"the",
"correct",
"branch",
"and",
"not",
"a",
"pull",
"-",
"request",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/ci_checks.py#L43-L52 | train |
relekang/python-semantic-release | semantic_release/ci_checks.py | frigg | def frigg(branch: str):
"""
Performs necessary checks to ensure that the frigg build is one
that should create releases.
:param branch: The branch the environment should be running against.
"""
assert os.environ.get('FRIGG_BUILD_BRANCH') == branch
assert not os.environ.get('FRIGG_PULL_REQUEST') | python | def frigg(branch: str):
"""
Performs necessary checks to ensure that the frigg build is one
that should create releases.
:param branch: The branch the environment should be running against.
"""
assert os.environ.get('FRIGG_BUILD_BRANCH') == branch
assert not os.environ.get('FRIGG_PULL_REQUEST') | [
"def",
"frigg",
"(",
"branch",
":",
"str",
")",
":",
"assert",
"os",
".",
"environ",
".",
"get",
"(",
"'FRIGG_BUILD_BRANCH'",
")",
"==",
"branch",
"assert",
"not",
"os",
".",
"environ",
".",
"get",
"(",
"'FRIGG_PULL_REQUEST'",
")"
] | Performs necessary checks to ensure that the frigg build is one
that should create releases.
:param branch: The branch the environment should be running against. | [
"Performs",
"necessary",
"checks",
"to",
"ensure",
"that",
"the",
"frigg",
"build",
"is",
"one",
"that",
"should",
"create",
"releases",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/ci_checks.py#L56-L64 | train |
relekang/python-semantic-release | semantic_release/ci_checks.py | circle | def circle(branch: str):
"""
Performs necessary checks to ensure that the circle build is one
that should create releases.
:param branch: The branch the environment should be running against.
"""
assert os.environ.get('CIRCLE_BRANCH') == branch
assert not os.environ.get('CI_PULL_REQUEST') | python | def circle(branch: str):
"""
Performs necessary checks to ensure that the circle build is one
that should create releases.
:param branch: The branch the environment should be running against.
"""
assert os.environ.get('CIRCLE_BRANCH') == branch
assert not os.environ.get('CI_PULL_REQUEST') | [
"def",
"circle",
"(",
"branch",
":",
"str",
")",
":",
"assert",
"os",
".",
"environ",
".",
"get",
"(",
"'CIRCLE_BRANCH'",
")",
"==",
"branch",
"assert",
"not",
"os",
".",
"environ",
".",
"get",
"(",
"'CI_PULL_REQUEST'",
")"
] | Performs necessary checks to ensure that the circle build is one
that should create releases.
:param branch: The branch the environment should be running against. | [
"Performs",
"necessary",
"checks",
"to",
"ensure",
"that",
"the",
"circle",
"build",
"is",
"one",
"that",
"should",
"create",
"releases",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/ci_checks.py#L68-L76 | train |
relekang/python-semantic-release | semantic_release/ci_checks.py | bitbucket | def bitbucket(branch: str):
"""
Performs necessary checks to ensure that the bitbucket build is one
that should create releases.
:param branch: The branch the environment should be running against.
"""
assert os.environ.get('BITBUCKET_BRANCH') == branch
assert not os.environ.get('BITBUCKET_PR_ID') | python | def bitbucket(branch: str):
"""
Performs necessary checks to ensure that the bitbucket build is one
that should create releases.
:param branch: The branch the environment should be running against.
"""
assert os.environ.get('BITBUCKET_BRANCH') == branch
assert not os.environ.get('BITBUCKET_PR_ID') | [
"def",
"bitbucket",
"(",
"branch",
":",
"str",
")",
":",
"assert",
"os",
".",
"environ",
".",
"get",
"(",
"'BITBUCKET_BRANCH'",
")",
"==",
"branch",
"assert",
"not",
"os",
".",
"environ",
".",
"get",
"(",
"'BITBUCKET_PR_ID'",
")"
] | Performs necessary checks to ensure that the bitbucket build is one
that should create releases.
:param branch: The branch the environment should be running against. | [
"Performs",
"necessary",
"checks",
"to",
"ensure",
"that",
"the",
"bitbucket",
"build",
"is",
"one",
"that",
"should",
"create",
"releases",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/ci_checks.py#L92-L100 | train |
relekang/python-semantic-release | semantic_release/ci_checks.py | check | def check(branch: str = 'master'):
"""
Detects the current CI environment, if any, and performs necessary
environment checks.
:param branch: The branch that should be the current branch.
"""
if os.environ.get('TRAVIS') == 'true':
travis(branch)
elif os.environ.get('SEMAPHORE') == 'true':
semaphore(branch)
elif os.environ.get('FRIGG') == 'true':
frigg(branch)
elif os.environ.get('CIRCLECI') == 'true':
circle(branch)
elif os.environ.get('GITLAB_CI') == 'true':
gitlab(branch)
elif 'BITBUCKET_BUILD_NUMBER' in os.environ:
bitbucket(branch) | python | def check(branch: str = 'master'):
"""
Detects the current CI environment, if any, and performs necessary
environment checks.
:param branch: The branch that should be the current branch.
"""
if os.environ.get('TRAVIS') == 'true':
travis(branch)
elif os.environ.get('SEMAPHORE') == 'true':
semaphore(branch)
elif os.environ.get('FRIGG') == 'true':
frigg(branch)
elif os.environ.get('CIRCLECI') == 'true':
circle(branch)
elif os.environ.get('GITLAB_CI') == 'true':
gitlab(branch)
elif 'BITBUCKET_BUILD_NUMBER' in os.environ:
bitbucket(branch) | [
"def",
"check",
"(",
"branch",
":",
"str",
"=",
"'master'",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAVIS'",
")",
"==",
"'true'",
":",
"travis",
"(",
"branch",
")",
"elif",
"os",
".",
"environ",
".",
"get",
"(",
"'SEMAPHORE'",
")",
"==",
"'true'",
":",
"semaphore",
"(",
"branch",
")",
"elif",
"os",
".",
"environ",
".",
"get",
"(",
"'FRIGG'",
")",
"==",
"'true'",
":",
"frigg",
"(",
"branch",
")",
"elif",
"os",
".",
"environ",
".",
"get",
"(",
"'CIRCLECI'",
")",
"==",
"'true'",
":",
"circle",
"(",
"branch",
")",
"elif",
"os",
".",
"environ",
".",
"get",
"(",
"'GITLAB_CI'",
")",
"==",
"'true'",
":",
"gitlab",
"(",
"branch",
")",
"elif",
"'BITBUCKET_BUILD_NUMBER'",
"in",
"os",
".",
"environ",
":",
"bitbucket",
"(",
"branch",
")"
] | Detects the current CI environment, if any, and performs necessary
environment checks.
:param branch: The branch that should be the current branch. | [
"Detects",
"the",
"current",
"CI",
"environment",
"if",
"any",
"and",
"performs",
"necessary",
"environment",
"checks",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/ci_checks.py#L103-L121 | train |
relekang/python-semantic-release | semantic_release/history/parser_angular.py | parse_commit_message | def parse_commit_message(message: str) -> Tuple[int, str, str, Tuple[str, str, str]]:
"""
Parses a commit message according to the angular commit guidelines specification.
:param message: A string of a commit message.
:return: A tuple of (level to bump, type of change, scope of change, a tuple with descriptions)
:raises UnknownCommitMessageStyleError: if regular expression matching fails
"""
parsed = re_parser.match(message)
if not parsed:
raise UnknownCommitMessageStyleError(
'Unable to parse the given commit message: {}'.format(message)
)
level_bump = 0
if parsed.group('text') and 'BREAKING CHANGE' in parsed.group('text'):
level_bump = 3
if parsed.group('type') == 'feat':
level_bump = max([level_bump, 2])
if parsed.group('type') == 'fix':
level_bump = max([level_bump, 1])
body, footer = parse_text_block(parsed.group('text'))
if debug.enabled:
debug('parse_commit_message -> ({}, {}, {}, {})'.format(
level_bump,
TYPES[parsed.group('type')],
parsed.group('scope'),
(parsed.group('subject'), body, footer)
))
return (
level_bump,
TYPES[parsed.group('type')],
parsed.group('scope'),
(parsed.group('subject'), body, footer)
) | python | def parse_commit_message(message: str) -> Tuple[int, str, str, Tuple[str, str, str]]:
"""
Parses a commit message according to the angular commit guidelines specification.
:param message: A string of a commit message.
:return: A tuple of (level to bump, type of change, scope of change, a tuple with descriptions)
:raises UnknownCommitMessageStyleError: if regular expression matching fails
"""
parsed = re_parser.match(message)
if not parsed:
raise UnknownCommitMessageStyleError(
'Unable to parse the given commit message: {}'.format(message)
)
level_bump = 0
if parsed.group('text') and 'BREAKING CHANGE' in parsed.group('text'):
level_bump = 3
if parsed.group('type') == 'feat':
level_bump = max([level_bump, 2])
if parsed.group('type') == 'fix':
level_bump = max([level_bump, 1])
body, footer = parse_text_block(parsed.group('text'))
if debug.enabled:
debug('parse_commit_message -> ({}, {}, {}, {})'.format(
level_bump,
TYPES[parsed.group('type')],
parsed.group('scope'),
(parsed.group('subject'), body, footer)
))
return (
level_bump,
TYPES[parsed.group('type')],
parsed.group('scope'),
(parsed.group('subject'), body, footer)
) | [
"def",
"parse_commit_message",
"(",
"message",
":",
"str",
")",
"->",
"Tuple",
"[",
"int",
",",
"str",
",",
"str",
",",
"Tuple",
"[",
"str",
",",
"str",
",",
"str",
"]",
"]",
":",
"parsed",
"=",
"re_parser",
".",
"match",
"(",
"message",
")",
"if",
"not",
"parsed",
":",
"raise",
"UnknownCommitMessageStyleError",
"(",
"'Unable to parse the given commit message: {}'",
".",
"format",
"(",
"message",
")",
")",
"level_bump",
"=",
"0",
"if",
"parsed",
".",
"group",
"(",
"'text'",
")",
"and",
"'BREAKING CHANGE'",
"in",
"parsed",
".",
"group",
"(",
"'text'",
")",
":",
"level_bump",
"=",
"3",
"if",
"parsed",
".",
"group",
"(",
"'type'",
")",
"==",
"'feat'",
":",
"level_bump",
"=",
"max",
"(",
"[",
"level_bump",
",",
"2",
"]",
")",
"if",
"parsed",
".",
"group",
"(",
"'type'",
")",
"==",
"'fix'",
":",
"level_bump",
"=",
"max",
"(",
"[",
"level_bump",
",",
"1",
"]",
")",
"body",
",",
"footer",
"=",
"parse_text_block",
"(",
"parsed",
".",
"group",
"(",
"'text'",
")",
")",
"if",
"debug",
".",
"enabled",
":",
"debug",
"(",
"'parse_commit_message -> ({}, {}, {}, {})'",
".",
"format",
"(",
"level_bump",
",",
"TYPES",
"[",
"parsed",
".",
"group",
"(",
"'type'",
")",
"]",
",",
"parsed",
".",
"group",
"(",
"'scope'",
")",
",",
"(",
"parsed",
".",
"group",
"(",
"'subject'",
")",
",",
"body",
",",
"footer",
")",
")",
")",
"return",
"(",
"level_bump",
",",
"TYPES",
"[",
"parsed",
".",
"group",
"(",
"'type'",
")",
"]",
",",
"parsed",
".",
"group",
"(",
"'scope'",
")",
",",
"(",
"parsed",
".",
"group",
"(",
"'subject'",
")",
",",
"body",
",",
"footer",
")",
")"
] | Parses a commit message according to the angular commit guidelines specification.
:param message: A string of a commit message.
:return: A tuple of (level to bump, type of change, scope of change, a tuple with descriptions)
:raises UnknownCommitMessageStyleError: if regular expression matching fails | [
"Parses",
"a",
"commit",
"message",
"according",
"to",
"the",
"angular",
"commit",
"guidelines",
"specification",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/parser_angular.py#L32-L69 | train |
relekang/python-semantic-release | semantic_release/history/parser_helpers.py | parse_text_block | def parse_text_block(text: str) -> Tuple[str, str]:
"""
This will take a text block and return a tuple with body and footer,
where footer is defined as the last paragraph.
:param text: The text string to be divided.
:return: A tuple with body and footer,
where footer is defined as the last paragraph.
"""
body, footer = '', ''
if text:
body = text.split('\n\n')[0]
if len(text.split('\n\n')) == 2:
footer = text.split('\n\n')[1]
return body.replace('\n', ' '), footer.replace('\n', ' ') | python | def parse_text_block(text: str) -> Tuple[str, str]:
"""
This will take a text block and return a tuple with body and footer,
where footer is defined as the last paragraph.
:param text: The text string to be divided.
:return: A tuple with body and footer,
where footer is defined as the last paragraph.
"""
body, footer = '', ''
if text:
body = text.split('\n\n')[0]
if len(text.split('\n\n')) == 2:
footer = text.split('\n\n')[1]
return body.replace('\n', ' '), footer.replace('\n', ' ') | [
"def",
"parse_text_block",
"(",
"text",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"body",
",",
"footer",
"=",
"''",
",",
"''",
"if",
"text",
":",
"body",
"=",
"text",
".",
"split",
"(",
"'\\n\\n'",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"text",
".",
"split",
"(",
"'\\n\\n'",
")",
")",
"==",
"2",
":",
"footer",
"=",
"text",
".",
"split",
"(",
"'\\n\\n'",
")",
"[",
"1",
"]",
"return",
"body",
".",
"replace",
"(",
"'\\n'",
",",
"' '",
")",
",",
"footer",
".",
"replace",
"(",
"'\\n'",
",",
"' '",
")"
] | This will take a text block and return a tuple with body and footer,
where footer is defined as the last paragraph.
:param text: The text string to be divided.
:return: A tuple with body and footer,
where footer is defined as the last paragraph. | [
"This",
"will",
"take",
"a",
"text",
"block",
"and",
"return",
"a",
"tuple",
"with",
"body",
"and",
"footer",
"where",
"footer",
"is",
"defined",
"as",
"the",
"last",
"paragraph",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/parser_helpers.py#L6-L21 | train |
relekang/python-semantic-release | semantic_release/pypi.py | upload_to_pypi | def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:param dists: The dists string passed to setup.py. Default: 'bdist_wheel'
:param username: PyPI account username string
:param password: PyPI account password string
:param skip_existing: Continue uploading files if one already exists. (Only valid when
uploading to PyPI. Other implementations may not support this.)
"""
if username is None or password is None or username == "" or password == "":
raise ImproperConfigurationError('Missing credentials for uploading')
run('rm -rf build dist')
run('python setup.py {}'.format(dists))
run(
'twine upload -u {} -p {} {} {}'.format(
username,
password,
'--skip-existing' if skip_existing else '',
'dist/*'
)
)
run('rm -rf build dist') | python | def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:param dists: The dists string passed to setup.py. Default: 'bdist_wheel'
:param username: PyPI account username string
:param password: PyPI account password string
:param skip_existing: Continue uploading files if one already exists. (Only valid when
uploading to PyPI. Other implementations may not support this.)
"""
if username is None or password is None or username == "" or password == "":
raise ImproperConfigurationError('Missing credentials for uploading')
run('rm -rf build dist')
run('python setup.py {}'.format(dists))
run(
'twine upload -u {} -p {} {} {}'.format(
username,
password,
'--skip-existing' if skip_existing else '',
'dist/*'
)
)
run('rm -rf build dist') | [
"def",
"upload_to_pypi",
"(",
"dists",
":",
"str",
"=",
"'sdist bdist_wheel'",
",",
"username",
":",
"str",
"=",
"None",
",",
"password",
":",
"str",
"=",
"None",
",",
"skip_existing",
":",
"bool",
"=",
"False",
")",
":",
"if",
"username",
"is",
"None",
"or",
"password",
"is",
"None",
"or",
"username",
"==",
"\"\"",
"or",
"password",
"==",
"\"\"",
":",
"raise",
"ImproperConfigurationError",
"(",
"'Missing credentials for uploading'",
")",
"run",
"(",
"'rm -rf build dist'",
")",
"run",
"(",
"'python setup.py {}'",
".",
"format",
"(",
"dists",
")",
")",
"run",
"(",
"'twine upload -u {} -p {} {} {}'",
".",
"format",
"(",
"username",
",",
"password",
",",
"'--skip-existing'",
"if",
"skip_existing",
"else",
"''",
",",
"'dist/*'",
")",
")",
"run",
"(",
"'rm -rf build dist'",
")"
] | Creates the wheel and uploads to pypi with twine.
:param dists: The dists string passed to setup.py. Default: 'bdist_wheel'
:param username: PyPI account username string
:param password: PyPI account password string
:param skip_existing: Continue uploading files if one already exists. (Only valid when
uploading to PyPI. Other implementations may not support this.) | [
"Creates",
"the",
"wheel",
"and",
"uploads",
"to",
"pypi",
"with",
"twine",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/pypi.py#L8-L34 | train |
relekang/python-semantic-release | semantic_release/vcs_helpers.py | get_commit_log | def get_commit_log(from_rev=None):
"""
Yields all commit messages from last to first.
"""
check_repo()
rev = None
if from_rev:
rev = '...{from_rev}'.format(from_rev=from_rev)
for commit in repo.iter_commits(rev):
yield (commit.hexsha, commit.message) | python | def get_commit_log(from_rev=None):
"""
Yields all commit messages from last to first.
"""
check_repo()
rev = None
if from_rev:
rev = '...{from_rev}'.format(from_rev=from_rev)
for commit in repo.iter_commits(rev):
yield (commit.hexsha, commit.message) | [
"def",
"get_commit_log",
"(",
"from_rev",
"=",
"None",
")",
":",
"check_repo",
"(",
")",
"rev",
"=",
"None",
"if",
"from_rev",
":",
"rev",
"=",
"'...{from_rev}'",
".",
"format",
"(",
"from_rev",
"=",
"from_rev",
")",
"for",
"commit",
"in",
"repo",
".",
"iter_commits",
"(",
"rev",
")",
":",
"yield",
"(",
"commit",
".",
"hexsha",
",",
"commit",
".",
"message",
")"
] | Yields all commit messages from last to first. | [
"Yields",
"all",
"commit",
"messages",
"from",
"last",
"to",
"first",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/vcs_helpers.py#L25-L35 | train |
relekang/python-semantic-release | semantic_release/vcs_helpers.py | get_last_version | def get_last_version(skip_tags=None) -> Optional[str]:
"""
Return last version from repo tags.
:return: A string contains version number.
"""
debug('get_last_version skip_tags=', skip_tags)
check_repo()
skip_tags = skip_tags or []
def version_finder(tag):
if isinstance(tag.commit, TagObject):
return tag.tag.tagged_date
return tag.commit.committed_date
for i in sorted(repo.tags, reverse=True, key=version_finder):
if re.match(r'v\d+\.\d+\.\d+', i.name):
if i.name in skip_tags:
continue
return i.name[1:]
return None | python | def get_last_version(skip_tags=None) -> Optional[str]:
"""
Return last version from repo tags.
:return: A string contains version number.
"""
debug('get_last_version skip_tags=', skip_tags)
check_repo()
skip_tags = skip_tags or []
def version_finder(tag):
if isinstance(tag.commit, TagObject):
return tag.tag.tagged_date
return tag.commit.committed_date
for i in sorted(repo.tags, reverse=True, key=version_finder):
if re.match(r'v\d+\.\d+\.\d+', i.name):
if i.name in skip_tags:
continue
return i.name[1:]
return None | [
"def",
"get_last_version",
"(",
"skip_tags",
"=",
"None",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"debug",
"(",
"'get_last_version skip_tags='",
",",
"skip_tags",
")",
"check_repo",
"(",
")",
"skip_tags",
"=",
"skip_tags",
"or",
"[",
"]",
"def",
"version_finder",
"(",
"tag",
")",
":",
"if",
"isinstance",
"(",
"tag",
".",
"commit",
",",
"TagObject",
")",
":",
"return",
"tag",
".",
"tag",
".",
"tagged_date",
"return",
"tag",
".",
"commit",
".",
"committed_date",
"for",
"i",
"in",
"sorted",
"(",
"repo",
".",
"tags",
",",
"reverse",
"=",
"True",
",",
"key",
"=",
"version_finder",
")",
":",
"if",
"re",
".",
"match",
"(",
"r'v\\d+\\.\\d+\\.\\d+'",
",",
"i",
".",
"name",
")",
":",
"if",
"i",
".",
"name",
"in",
"skip_tags",
":",
"continue",
"return",
"i",
".",
"name",
"[",
"1",
":",
"]",
"return",
"None"
] | Return last version from repo tags.
:return: A string contains version number. | [
"Return",
"last",
"version",
"from",
"repo",
"tags",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/vcs_helpers.py#L38-L59 | train |
relekang/python-semantic-release | semantic_release/vcs_helpers.py | get_version_from_tag | def get_version_from_tag(tag_name: str) -> Optional[str]:
"""Get git hash from tag
:param tag_name: Name of the git tag (i.e. 'v1.0.0')
:return: sha1 hash of the commit
"""
debug('get_version_from_tag({})'.format(tag_name))
check_repo()
for i in repo.tags:
if i.name == tag_name:
return i.commit.hexsha
return None | python | def get_version_from_tag(tag_name: str) -> Optional[str]:
"""Get git hash from tag
:param tag_name: Name of the git tag (i.e. 'v1.0.0')
:return: sha1 hash of the commit
"""
debug('get_version_from_tag({})'.format(tag_name))
check_repo()
for i in repo.tags:
if i.name == tag_name:
return i.commit.hexsha
return None | [
"def",
"get_version_from_tag",
"(",
"tag_name",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"debug",
"(",
"'get_version_from_tag({})'",
".",
"format",
"(",
"tag_name",
")",
")",
"check_repo",
"(",
")",
"for",
"i",
"in",
"repo",
".",
"tags",
":",
"if",
"i",
".",
"name",
"==",
"tag_name",
":",
"return",
"i",
".",
"commit",
".",
"hexsha",
"return",
"None"
] | Get git hash from tag
:param tag_name: Name of the git tag (i.e. 'v1.0.0')
:return: sha1 hash of the commit | [
"Get",
"git",
"hash",
"from",
"tag"
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/vcs_helpers.py#L62-L74 | train |
relekang/python-semantic-release | semantic_release/vcs_helpers.py | get_repository_owner_and_name | def get_repository_owner_and_name() -> Tuple[str, str]:
"""
Checks the origin remote to get the owner and name of the remote repository.
:return: A tuple of the owner and name.
"""
check_repo()
url = repo.remote('origin').url
parts = re.search(r'([^/:]+)/([^/]+).git$', url)
if not parts:
raise HvcsRepoParseError
debug('get_repository_owner_and_name', parts)
return parts.group(1), parts.group(2) | python | def get_repository_owner_and_name() -> Tuple[str, str]:
"""
Checks the origin remote to get the owner and name of the remote repository.
:return: A tuple of the owner and name.
"""
check_repo()
url = repo.remote('origin').url
parts = re.search(r'([^/:]+)/([^/]+).git$', url)
if not parts:
raise HvcsRepoParseError
debug('get_repository_owner_and_name', parts)
return parts.group(1), parts.group(2) | [
"def",
"get_repository_owner_and_name",
"(",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"check_repo",
"(",
")",
"url",
"=",
"repo",
".",
"remote",
"(",
"'origin'",
")",
".",
"url",
"parts",
"=",
"re",
".",
"search",
"(",
"r'([^/:]+)/([^/]+).git$'",
",",
"url",
")",
"if",
"not",
"parts",
":",
"raise",
"HvcsRepoParseError",
"debug",
"(",
"'get_repository_owner_and_name'",
",",
"parts",
")",
"return",
"parts",
".",
"group",
"(",
"1",
")",
",",
"parts",
".",
"group",
"(",
"2",
")"
] | Checks the origin remote to get the owner and name of the remote repository.
:return: A tuple of the owner and name. | [
"Checks",
"the",
"origin",
"remote",
"to",
"get",
"the",
"owner",
"and",
"name",
"of",
"the",
"remote",
"repository",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/vcs_helpers.py#L77-L90 | train |
relekang/python-semantic-release | semantic_release/vcs_helpers.py | commit_new_version | def commit_new_version(version: str):
"""
Commits the file containing the version number variable with the version number as the commit
message.
:param version: The version number to be used in the commit message.
"""
check_repo()
commit_message = config.get('semantic_release', 'commit_message')
message = '{0}\n\n{1}'.format(version, commit_message)
repo.git.add(config.get('semantic_release', 'version_variable').split(':')[0])
return repo.git.commit(m=message, author="semantic-release <semantic-release>") | python | def commit_new_version(version: str):
"""
Commits the file containing the version number variable with the version number as the commit
message.
:param version: The version number to be used in the commit message.
"""
check_repo()
commit_message = config.get('semantic_release', 'commit_message')
message = '{0}\n\n{1}'.format(version, commit_message)
repo.git.add(config.get('semantic_release', 'version_variable').split(':')[0])
return repo.git.commit(m=message, author="semantic-release <semantic-release>") | [
"def",
"commit_new_version",
"(",
"version",
":",
"str",
")",
":",
"check_repo",
"(",
")",
"commit_message",
"=",
"config",
".",
"get",
"(",
"'semantic_release'",
",",
"'commit_message'",
")",
"message",
"=",
"'{0}\\n\\n{1}'",
".",
"format",
"(",
"version",
",",
"commit_message",
")",
"repo",
".",
"git",
".",
"add",
"(",
"config",
".",
"get",
"(",
"'semantic_release'",
",",
"'version_variable'",
")",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
")",
"return",
"repo",
".",
"git",
".",
"commit",
"(",
"m",
"=",
"message",
",",
"author",
"=",
"\"semantic-release <semantic-release>\"",
")"
] | Commits the file containing the version number variable with the version number as the commit
message.
:param version: The version number to be used in the commit message. | [
"Commits",
"the",
"file",
"containing",
"the",
"version",
"number",
"variable",
"with",
"the",
"version",
"number",
"as",
"the",
"commit",
"message",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/vcs_helpers.py#L104-L116 | train |
relekang/python-semantic-release | semantic_release/vcs_helpers.py | tag_new_version | def tag_new_version(version: str):
"""
Creates a new tag with the version number prefixed with v.
:param version: The version number used in the tag as a string.
"""
check_repo()
return repo.git.tag('-a', 'v{0}'.format(version), m='v{0}'.format(version)) | python | def tag_new_version(version: str):
"""
Creates a new tag with the version number prefixed with v.
:param version: The version number used in the tag as a string.
"""
check_repo()
return repo.git.tag('-a', 'v{0}'.format(version), m='v{0}'.format(version)) | [
"def",
"tag_new_version",
"(",
"version",
":",
"str",
")",
":",
"check_repo",
"(",
")",
"return",
"repo",
".",
"git",
".",
"tag",
"(",
"'-a'",
",",
"'v{0}'",
".",
"format",
"(",
"version",
")",
",",
"m",
"=",
"'v{0}'",
".",
"format",
"(",
"version",
")",
")"
] | Creates a new tag with the version number prefixed with v.
:param version: The version number used in the tag as a string. | [
"Creates",
"a",
"new",
"tag",
"with",
"the",
"version",
"number",
"prefixed",
"with",
"v",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/vcs_helpers.py#L119-L127 | train |
relekang/python-semantic-release | semantic_release/settings.py | current_commit_parser | def current_commit_parser() -> Callable:
"""Current commit parser
:raises ImproperConfigurationError: if ImportError or AttributeError is raised
"""
try:
parts = config.get('semantic_release', 'commit_parser').split('.')
module = '.'.join(parts[:-1])
return getattr(importlib.import_module(module), parts[-1])
except (ImportError, AttributeError) as error:
raise ImproperConfigurationError('Unable to import parser "{}"'.format(error)) | python | def current_commit_parser() -> Callable:
"""Current commit parser
:raises ImproperConfigurationError: if ImportError or AttributeError is raised
"""
try:
parts = config.get('semantic_release', 'commit_parser').split('.')
module = '.'.join(parts[:-1])
return getattr(importlib.import_module(module), parts[-1])
except (ImportError, AttributeError) as error:
raise ImproperConfigurationError('Unable to import parser "{}"'.format(error)) | [
"def",
"current_commit_parser",
"(",
")",
"->",
"Callable",
":",
"try",
":",
"parts",
"=",
"config",
".",
"get",
"(",
"'semantic_release'",
",",
"'commit_parser'",
")",
".",
"split",
"(",
"'.'",
")",
"module",
"=",
"'.'",
".",
"join",
"(",
"parts",
"[",
":",
"-",
"1",
"]",
")",
"return",
"getattr",
"(",
"importlib",
".",
"import_module",
"(",
"module",
")",
",",
"parts",
"[",
"-",
"1",
"]",
")",
"except",
"(",
"ImportError",
",",
"AttributeError",
")",
"as",
"error",
":",
"raise",
"ImproperConfigurationError",
"(",
"'Unable to import parser \"{}\"'",
".",
"format",
"(",
"error",
")",
")"
] | Current commit parser
:raises ImproperConfigurationError: if ImportError or AttributeError is raised | [
"Current",
"commit",
"parser"
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/settings.py#L24-L35 | train |
relekang/python-semantic-release | semantic_release/history/__init__.py | get_current_version_by_config_file | def get_current_version_by_config_file() -> str:
"""
Get current version from the version variable defined in the configuration
:return: A string with the current version number
:raises ImproperConfigurationError: if version variable cannot be parsed
"""
debug('get_current_version_by_config_file')
filename, variable = config.get('semantic_release',
'version_variable').split(':')
variable = variable.strip()
debug(filename, variable)
with open(filename, 'r') as fd:
parts = re.search(
r'^{0}\s*=\s*[\'"]([^\'"]*)[\'"]'.format(variable),
fd.read(),
re.MULTILINE
)
if not parts:
raise ImproperConfigurationError
debug(parts)
return parts.group(1) | python | def get_current_version_by_config_file() -> str:
"""
Get current version from the version variable defined in the configuration
:return: A string with the current version number
:raises ImproperConfigurationError: if version variable cannot be parsed
"""
debug('get_current_version_by_config_file')
filename, variable = config.get('semantic_release',
'version_variable').split(':')
variable = variable.strip()
debug(filename, variable)
with open(filename, 'r') as fd:
parts = re.search(
r'^{0}\s*=\s*[\'"]([^\'"]*)[\'"]'.format(variable),
fd.read(),
re.MULTILINE
)
if not parts:
raise ImproperConfigurationError
debug(parts)
return parts.group(1) | [
"def",
"get_current_version_by_config_file",
"(",
")",
"->",
"str",
":",
"debug",
"(",
"'get_current_version_by_config_file'",
")",
"filename",
",",
"variable",
"=",
"config",
".",
"get",
"(",
"'semantic_release'",
",",
"'version_variable'",
")",
".",
"split",
"(",
"':'",
")",
"variable",
"=",
"variable",
".",
"strip",
"(",
")",
"debug",
"(",
"filename",
",",
"variable",
")",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fd",
":",
"parts",
"=",
"re",
".",
"search",
"(",
"r'^{0}\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]'",
".",
"format",
"(",
"variable",
")",
",",
"fd",
".",
"read",
"(",
")",
",",
"re",
".",
"MULTILINE",
")",
"if",
"not",
"parts",
":",
"raise",
"ImproperConfigurationError",
"debug",
"(",
"parts",
")",
"return",
"parts",
".",
"group",
"(",
"1",
")"
] | Get current version from the version variable defined in the configuration
:return: A string with the current version number
:raises ImproperConfigurationError: if version variable cannot be parsed | [
"Get",
"current",
"version",
"from",
"the",
"version",
"variable",
"defined",
"in",
"the",
"configuration"
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/__init__.py#L34-L55 | train |
relekang/python-semantic-release | semantic_release/history/__init__.py | get_new_version | def get_new_version(current_version: str, level_bump: str) -> str:
"""
Calculates the next version based on the given bump level with semver.
:param current_version: The version the package has now.
:param level_bump: The level of the version number that should be bumped. Should be a `'major'`,
`'minor'` or `'patch'`.
:return: A string with the next version number.
"""
debug('get_new_version("{}", "{}")'.format(current_version, level_bump))
if not level_bump:
return current_version
return getattr(semver, 'bump_{0}'.format(level_bump))(current_version) | python | def get_new_version(current_version: str, level_bump: str) -> str:
"""
Calculates the next version based on the given bump level with semver.
:param current_version: The version the package has now.
:param level_bump: The level of the version number that should be bumped. Should be a `'major'`,
`'minor'` or `'patch'`.
:return: A string with the next version number.
"""
debug('get_new_version("{}", "{}")'.format(current_version, level_bump))
if not level_bump:
return current_version
return getattr(semver, 'bump_{0}'.format(level_bump))(current_version) | [
"def",
"get_new_version",
"(",
"current_version",
":",
"str",
",",
"level_bump",
":",
"str",
")",
"->",
"str",
":",
"debug",
"(",
"'get_new_version(\"{}\", \"{}\")'",
".",
"format",
"(",
"current_version",
",",
"level_bump",
")",
")",
"if",
"not",
"level_bump",
":",
"return",
"current_version",
"return",
"getattr",
"(",
"semver",
",",
"'bump_{0}'",
".",
"format",
"(",
"level_bump",
")",
")",
"(",
"current_version",
")"
] | Calculates the next version based on the given bump level with semver.
:param current_version: The version the package has now.
:param level_bump: The level of the version number that should be bumped. Should be a `'major'`,
`'minor'` or `'patch'`.
:return: A string with the next version number. | [
"Calculates",
"the",
"next",
"version",
"based",
"on",
"the",
"given",
"bump",
"level",
"with",
"semver",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/__init__.py#L69-L81 | train |
relekang/python-semantic-release | semantic_release/history/__init__.py | get_previous_version | def get_previous_version(version: str) -> Optional[str]:
"""
Returns the version prior to the given version.
:param version: A string with the version number.
:return: A string with the previous version number
"""
debug('get_previous_version')
found_version = False
for commit_hash, commit_message in get_commit_log():
debug('checking commit {}'.format(commit_hash))
if version in commit_message:
found_version = True
debug('found_version in "{}"'.format(commit_message))
continue
if found_version:
matches = re.match(r'v?(\d+.\d+.\d+)', commit_message)
if matches:
debug('version matches', commit_message)
return matches.group(1).strip()
return get_last_version([version, 'v{}'.format(version)]) | python | def get_previous_version(version: str) -> Optional[str]:
"""
Returns the version prior to the given version.
:param version: A string with the version number.
:return: A string with the previous version number
"""
debug('get_previous_version')
found_version = False
for commit_hash, commit_message in get_commit_log():
debug('checking commit {}'.format(commit_hash))
if version in commit_message:
found_version = True
debug('found_version in "{}"'.format(commit_message))
continue
if found_version:
matches = re.match(r'v?(\d+.\d+.\d+)', commit_message)
if matches:
debug('version matches', commit_message)
return matches.group(1).strip()
return get_last_version([version, 'v{}'.format(version)]) | [
"def",
"get_previous_version",
"(",
"version",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"debug",
"(",
"'get_previous_version'",
")",
"found_version",
"=",
"False",
"for",
"commit_hash",
",",
"commit_message",
"in",
"get_commit_log",
"(",
")",
":",
"debug",
"(",
"'checking commit {}'",
".",
"format",
"(",
"commit_hash",
")",
")",
"if",
"version",
"in",
"commit_message",
":",
"found_version",
"=",
"True",
"debug",
"(",
"'found_version in \"{}\"'",
".",
"format",
"(",
"commit_message",
")",
")",
"continue",
"if",
"found_version",
":",
"matches",
"=",
"re",
".",
"match",
"(",
"r'v?(\\d+.\\d+.\\d+)'",
",",
"commit_message",
")",
"if",
"matches",
":",
"debug",
"(",
"'version matches'",
",",
"commit_message",
")",
"return",
"matches",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"return",
"get_last_version",
"(",
"[",
"version",
",",
"'v{}'",
".",
"format",
"(",
"version",
")",
"]",
")"
] | Returns the version prior to the given version.
:param version: A string with the version number.
:return: A string with the previous version number | [
"Returns",
"the",
"version",
"prior",
"to",
"the",
"given",
"version",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/__init__.py#L84-L106 | train |
relekang/python-semantic-release | semantic_release/history/__init__.py | replace_version_string | def replace_version_string(content, variable, new_version):
"""
Given the content of a file, finds the version string and updates it.
:param content: The file contents
:param variable: The version variable name as a string
:param new_version: The new version number as a string
:return: A string with the updated version number
"""
return re.sub(
r'({0} ?= ?["\'])\d+\.\d+(?:\.\d+)?(["\'])'.format(variable),
r'\g<1>{0}\g<2>'.format(new_version),
content
) | python | def replace_version_string(content, variable, new_version):
"""
Given the content of a file, finds the version string and updates it.
:param content: The file contents
:param variable: The version variable name as a string
:param new_version: The new version number as a string
:return: A string with the updated version number
"""
return re.sub(
r'({0} ?= ?["\'])\d+\.\d+(?:\.\d+)?(["\'])'.format(variable),
r'\g<1>{0}\g<2>'.format(new_version),
content
) | [
"def",
"replace_version_string",
"(",
"content",
",",
"variable",
",",
"new_version",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'({0} ?= ?[\"\\'])\\d+\\.\\d+(?:\\.\\d+)?([\"\\'])'",
".",
"format",
"(",
"variable",
")",
",",
"r'\\g<1>{0}\\g<2>'",
".",
"format",
"(",
"new_version",
")",
",",
"content",
")"
] | Given the content of a file, finds the version string and updates it.
:param content: The file contents
:param variable: The version variable name as a string
:param new_version: The new version number as a string
:return: A string with the updated version number | [
"Given",
"the",
"content",
"of",
"a",
"file",
"finds",
"the",
"version",
"string",
"and",
"updates",
"it",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/__init__.py#L109-L122 | train |
relekang/python-semantic-release | semantic_release/history/__init__.py | set_new_version | def set_new_version(new_version: str) -> bool:
"""
Replaces the version number in the correct place and writes the changed file to disk.
:param new_version: The new version number as a string.
:return: `True` if it succeeded.
"""
filename, variable = config.get(
'semantic_release', 'version_variable').split(':')
variable = variable.strip()
with open(filename, mode='r') as fr:
content = fr.read()
content = replace_version_string(content, variable, new_version)
with open(filename, mode='w') as fw:
fw.write(content)
return True | python | def set_new_version(new_version: str) -> bool:
"""
Replaces the version number in the correct place and writes the changed file to disk.
:param new_version: The new version number as a string.
:return: `True` if it succeeded.
"""
filename, variable = config.get(
'semantic_release', 'version_variable').split(':')
variable = variable.strip()
with open(filename, mode='r') as fr:
content = fr.read()
content = replace_version_string(content, variable, new_version)
with open(filename, mode='w') as fw:
fw.write(content)
return True | [
"def",
"set_new_version",
"(",
"new_version",
":",
"str",
")",
"->",
"bool",
":",
"filename",
",",
"variable",
"=",
"config",
".",
"get",
"(",
"'semantic_release'",
",",
"'version_variable'",
")",
".",
"split",
"(",
"':'",
")",
"variable",
"=",
"variable",
".",
"strip",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"mode",
"=",
"'r'",
")",
"as",
"fr",
":",
"content",
"=",
"fr",
".",
"read",
"(",
")",
"content",
"=",
"replace_version_string",
"(",
"content",
",",
"variable",
",",
"new_version",
")",
"with",
"open",
"(",
"filename",
",",
"mode",
"=",
"'w'",
")",
"as",
"fw",
":",
"fw",
".",
"write",
"(",
"content",
")",
"return",
"True"
] | Replaces the version number in the correct place and writes the changed file to disk.
:param new_version: The new version number as a string.
:return: `True` if it succeeded. | [
"Replaces",
"the",
"version",
"number",
"in",
"the",
"correct",
"place",
"and",
"writes",
"the",
"changed",
"file",
"to",
"disk",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/__init__.py#L125-L142 | train |
relekang/python-semantic-release | semantic_release/history/logs.py | evaluate_version_bump | def evaluate_version_bump(current_version: str, force: str = None) -> Optional[str]:
"""
Reads git log since last release to find out if should be a major, minor or patch release.
:param current_version: A string with the current version number.
:param force: A string with the bump level that should be forced.
:return: A string with either major, minor or patch if there should be a release. If no release
is necessary None will be returned.
"""
debug('evaluate_version_bump("{}", "{}")'.format(current_version, force))
if force:
return force
bump = None
changes = []
commit_count = 0
for _hash, commit_message in get_commit_log('v{0}'.format(current_version)):
if (current_version in commit_message and
config.get('semantic_release', 'version_source') == 'commit'):
debug('found {} in "{}. breaking loop'.format(current_version, commit_message))
break
try:
message = current_commit_parser()(commit_message)
changes.append(message[0])
except UnknownCommitMessageStyleError as err:
debug('ignored', err)
pass
commit_count += 1
if changes:
level = max(changes)
if level in LEVELS:
bump = LEVELS[level]
if config.getboolean('semantic_release', 'patch_without_tag') and commit_count:
bump = 'patch'
return bump | python | def evaluate_version_bump(current_version: str, force: str = None) -> Optional[str]:
"""
Reads git log since last release to find out if should be a major, minor or patch release.
:param current_version: A string with the current version number.
:param force: A string with the bump level that should be forced.
:return: A string with either major, minor or patch if there should be a release. If no release
is necessary None will be returned.
"""
debug('evaluate_version_bump("{}", "{}")'.format(current_version, force))
if force:
return force
bump = None
changes = []
commit_count = 0
for _hash, commit_message in get_commit_log('v{0}'.format(current_version)):
if (current_version in commit_message and
config.get('semantic_release', 'version_source') == 'commit'):
debug('found {} in "{}. breaking loop'.format(current_version, commit_message))
break
try:
message = current_commit_parser()(commit_message)
changes.append(message[0])
except UnknownCommitMessageStyleError as err:
debug('ignored', err)
pass
commit_count += 1
if changes:
level = max(changes)
if level in LEVELS:
bump = LEVELS[level]
if config.getboolean('semantic_release', 'patch_without_tag') and commit_count:
bump = 'patch'
return bump | [
"def",
"evaluate_version_bump",
"(",
"current_version",
":",
"str",
",",
"force",
":",
"str",
"=",
"None",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"debug",
"(",
"'evaluate_version_bump(\"{}\", \"{}\")'",
".",
"format",
"(",
"current_version",
",",
"force",
")",
")",
"if",
"force",
":",
"return",
"force",
"bump",
"=",
"None",
"changes",
"=",
"[",
"]",
"commit_count",
"=",
"0",
"for",
"_hash",
",",
"commit_message",
"in",
"get_commit_log",
"(",
"'v{0}'",
".",
"format",
"(",
"current_version",
")",
")",
":",
"if",
"(",
"current_version",
"in",
"commit_message",
"and",
"config",
".",
"get",
"(",
"'semantic_release'",
",",
"'version_source'",
")",
"==",
"'commit'",
")",
":",
"debug",
"(",
"'found {} in \"{}. breaking loop'",
".",
"format",
"(",
"current_version",
",",
"commit_message",
")",
")",
"break",
"try",
":",
"message",
"=",
"current_commit_parser",
"(",
")",
"(",
"commit_message",
")",
"changes",
".",
"append",
"(",
"message",
"[",
"0",
"]",
")",
"except",
"UnknownCommitMessageStyleError",
"as",
"err",
":",
"debug",
"(",
"'ignored'",
",",
"err",
")",
"pass",
"commit_count",
"+=",
"1",
"if",
"changes",
":",
"level",
"=",
"max",
"(",
"changes",
")",
"if",
"level",
"in",
"LEVELS",
":",
"bump",
"=",
"LEVELS",
"[",
"level",
"]",
"if",
"config",
".",
"getboolean",
"(",
"'semantic_release'",
",",
"'patch_without_tag'",
")",
"and",
"commit_count",
":",
"bump",
"=",
"'patch'",
"return",
"bump"
] | Reads git log since last release to find out if should be a major, minor or patch release.
:param current_version: A string with the current version number.
:param force: A string with the bump level that should be forced.
:return: A string with either major, minor or patch if there should be a release. If no release
is necessary None will be returned. | [
"Reads",
"git",
"log",
"since",
"last",
"release",
"to",
"find",
"out",
"if",
"should",
"be",
"a",
"major",
"minor",
"or",
"patch",
"release",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/logs.py#L25-L63 | train |
relekang/python-semantic-release | semantic_release/history/logs.py | generate_changelog | def generate_changelog(from_version: str, to_version: str = None) -> dict:
"""
Generates a changelog for the given version.
:param from_version: The last version not in the changelog. The changelog
will be generated from the commit after this one.
:param to_version: The last version in the changelog.
:return: a dict with different changelog sections
"""
debug('generate_changelog("{}", "{}")'.format(from_version, to_version))
changes: dict = {'feature': [], 'fix': [],
'documentation': [], 'refactor': [], 'breaking': []}
found_the_release = to_version is None
rev = None
if from_version:
rev = 'v{0}'.format(from_version)
for _hash, commit_message in get_commit_log(rev):
if not found_the_release:
if to_version and to_version not in commit_message:
continue
else:
found_the_release = True
if from_version is not None and from_version in commit_message:
break
try:
message = current_commit_parser()(commit_message)
if message[1] not in changes:
continue
changes[message[1]].append((_hash, message[3][0]))
if message[3][1] and 'BREAKING CHANGE' in message[3][1]:
parts = re_breaking.match(message[3][1])
if parts:
changes['breaking'].append(parts.group(1))
if message[3][2] and 'BREAKING CHANGE' in message[3][2]:
parts = re_breaking.match(message[3][2])
if parts:
changes['breaking'].append(parts.group(1))
except UnknownCommitMessageStyleError as err:
debug('Ignoring', err)
pass
return changes | python | def generate_changelog(from_version: str, to_version: str = None) -> dict:
"""
Generates a changelog for the given version.
:param from_version: The last version not in the changelog. The changelog
will be generated from the commit after this one.
:param to_version: The last version in the changelog.
:return: a dict with different changelog sections
"""
debug('generate_changelog("{}", "{}")'.format(from_version, to_version))
changes: dict = {'feature': [], 'fix': [],
'documentation': [], 'refactor': [], 'breaking': []}
found_the_release = to_version is None
rev = None
if from_version:
rev = 'v{0}'.format(from_version)
for _hash, commit_message in get_commit_log(rev):
if not found_the_release:
if to_version and to_version not in commit_message:
continue
else:
found_the_release = True
if from_version is not None and from_version in commit_message:
break
try:
message = current_commit_parser()(commit_message)
if message[1] not in changes:
continue
changes[message[1]].append((_hash, message[3][0]))
if message[3][1] and 'BREAKING CHANGE' in message[3][1]:
parts = re_breaking.match(message[3][1])
if parts:
changes['breaking'].append(parts.group(1))
if message[3][2] and 'BREAKING CHANGE' in message[3][2]:
parts = re_breaking.match(message[3][2])
if parts:
changes['breaking'].append(parts.group(1))
except UnknownCommitMessageStyleError as err:
debug('Ignoring', err)
pass
return changes | [
"def",
"generate_changelog",
"(",
"from_version",
":",
"str",
",",
"to_version",
":",
"str",
"=",
"None",
")",
"->",
"dict",
":",
"debug",
"(",
"'generate_changelog(\"{}\", \"{}\")'",
".",
"format",
"(",
"from_version",
",",
"to_version",
")",
")",
"changes",
":",
"dict",
"=",
"{",
"'feature'",
":",
"[",
"]",
",",
"'fix'",
":",
"[",
"]",
",",
"'documentation'",
":",
"[",
"]",
",",
"'refactor'",
":",
"[",
"]",
",",
"'breaking'",
":",
"[",
"]",
"}",
"found_the_release",
"=",
"to_version",
"is",
"None",
"rev",
"=",
"None",
"if",
"from_version",
":",
"rev",
"=",
"'v{0}'",
".",
"format",
"(",
"from_version",
")",
"for",
"_hash",
",",
"commit_message",
"in",
"get_commit_log",
"(",
"rev",
")",
":",
"if",
"not",
"found_the_release",
":",
"if",
"to_version",
"and",
"to_version",
"not",
"in",
"commit_message",
":",
"continue",
"else",
":",
"found_the_release",
"=",
"True",
"if",
"from_version",
"is",
"not",
"None",
"and",
"from_version",
"in",
"commit_message",
":",
"break",
"try",
":",
"message",
"=",
"current_commit_parser",
"(",
")",
"(",
"commit_message",
")",
"if",
"message",
"[",
"1",
"]",
"not",
"in",
"changes",
":",
"continue",
"changes",
"[",
"message",
"[",
"1",
"]",
"]",
".",
"append",
"(",
"(",
"_hash",
",",
"message",
"[",
"3",
"]",
"[",
"0",
"]",
")",
")",
"if",
"message",
"[",
"3",
"]",
"[",
"1",
"]",
"and",
"'BREAKING CHANGE'",
"in",
"message",
"[",
"3",
"]",
"[",
"1",
"]",
":",
"parts",
"=",
"re_breaking",
".",
"match",
"(",
"message",
"[",
"3",
"]",
"[",
"1",
"]",
")",
"if",
"parts",
":",
"changes",
"[",
"'breaking'",
"]",
".",
"append",
"(",
"parts",
".",
"group",
"(",
"1",
")",
")",
"if",
"message",
"[",
"3",
"]",
"[",
"2",
"]",
"and",
"'BREAKING CHANGE'",
"in",
"message",
"[",
"3",
"]",
"[",
"2",
"]",
":",
"parts",
"=",
"re_breaking",
".",
"match",
"(",
"message",
"[",
"3",
"]",
"[",
"2",
"]",
")",
"if",
"parts",
":",
"changes",
"[",
"'breaking'",
"]",
".",
"append",
"(",
"parts",
".",
"group",
"(",
"1",
")",
")",
"except",
"UnknownCommitMessageStyleError",
"as",
"err",
":",
"debug",
"(",
"'Ignoring'",
",",
"err",
")",
"pass",
"return",
"changes"
] | Generates a changelog for the given version.
:param from_version: The last version not in the changelog. The changelog
will be generated from the commit after this one.
:param to_version: The last version in the changelog.
:return: a dict with different changelog sections | [
"Generates",
"a",
"changelog",
"for",
"the",
"given",
"version",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/logs.py#L66-L116 | train |
relekang/python-semantic-release | semantic_release/history/logs.py | markdown_changelog | def markdown_changelog(version: str, changelog: dict, header: bool = False) -> str:
"""
Generates a markdown version of the changelog. Takes a parsed changelog dict from
generate_changelog.
:param version: A string with the version number.
:param changelog: A dict from generate_changelog.
:param header: A boolean that decides whether a header should be included or not.
:return: The markdown formatted changelog.
"""
debug('markdown_changelog(version="{}", header={}, changelog=...)'.format(version, header))
output = ''
if header:
output += '## v{0}\n'.format(version)
for section in CHANGELOG_SECTIONS:
if not changelog[section]:
continue
output += '\n### {0}\n'.format(section.capitalize())
for item in changelog[section]:
output += '* {0} ({1})\n'.format(item[1], item[0])
return output | python | def markdown_changelog(version: str, changelog: dict, header: bool = False) -> str:
"""
Generates a markdown version of the changelog. Takes a parsed changelog dict from
generate_changelog.
:param version: A string with the version number.
:param changelog: A dict from generate_changelog.
:param header: A boolean that decides whether a header should be included or not.
:return: The markdown formatted changelog.
"""
debug('markdown_changelog(version="{}", header={}, changelog=...)'.format(version, header))
output = ''
if header:
output += '## v{0}\n'.format(version)
for section in CHANGELOG_SECTIONS:
if not changelog[section]:
continue
output += '\n### {0}\n'.format(section.capitalize())
for item in changelog[section]:
output += '* {0} ({1})\n'.format(item[1], item[0])
return output | [
"def",
"markdown_changelog",
"(",
"version",
":",
"str",
",",
"changelog",
":",
"dict",
",",
"header",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"debug",
"(",
"'markdown_changelog(version=\"{}\", header={}, changelog=...)'",
".",
"format",
"(",
"version",
",",
"header",
")",
")",
"output",
"=",
"''",
"if",
"header",
":",
"output",
"+=",
"'## v{0}\\n'",
".",
"format",
"(",
"version",
")",
"for",
"section",
"in",
"CHANGELOG_SECTIONS",
":",
"if",
"not",
"changelog",
"[",
"section",
"]",
":",
"continue",
"output",
"+=",
"'\\n### {0}\\n'",
".",
"format",
"(",
"section",
".",
"capitalize",
"(",
")",
")",
"for",
"item",
"in",
"changelog",
"[",
"section",
"]",
":",
"output",
"+=",
"'* {0} ({1})\\n'",
".",
"format",
"(",
"item",
"[",
"1",
"]",
",",
"item",
"[",
"0",
"]",
")",
"return",
"output"
] | Generates a markdown version of the changelog. Takes a parsed changelog dict from
generate_changelog.
:param version: A string with the version number.
:param changelog: A dict from generate_changelog.
:param header: A boolean that decides whether a header should be included or not.
:return: The markdown formatted changelog. | [
"Generates",
"a",
"markdown",
"version",
"of",
"the",
"changelog",
".",
"Takes",
"a",
"parsed",
"changelog",
"dict",
"from",
"generate_changelog",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/logs.py#L119-L142 | train |
relekang/python-semantic-release | semantic_release/hvcs.py | get_hvcs | def get_hvcs() -> Base:
"""Get HVCS helper class
:raises ImproperConfigurationError: if the hvcs option provided is not valid
"""
hvcs = config.get('semantic_release', 'hvcs')
debug('get_hvcs: hvcs=', hvcs)
try:
return globals()[hvcs.capitalize()]
except KeyError:
raise ImproperConfigurationError('"{0}" is not a valid option for hvcs.') | python | def get_hvcs() -> Base:
"""Get HVCS helper class
:raises ImproperConfigurationError: if the hvcs option provided is not valid
"""
hvcs = config.get('semantic_release', 'hvcs')
debug('get_hvcs: hvcs=', hvcs)
try:
return globals()[hvcs.capitalize()]
except KeyError:
raise ImproperConfigurationError('"{0}" is not a valid option for hvcs.') | [
"def",
"get_hvcs",
"(",
")",
"->",
"Base",
":",
"hvcs",
"=",
"config",
".",
"get",
"(",
"'semantic_release'",
",",
"'hvcs'",
")",
"debug",
"(",
"'get_hvcs: hvcs='",
",",
"hvcs",
")",
"try",
":",
"return",
"globals",
"(",
")",
"[",
"hvcs",
".",
"capitalize",
"(",
")",
"]",
"except",
"KeyError",
":",
"raise",
"ImproperConfigurationError",
"(",
"'\"{0}\" is not a valid option for hvcs.'",
")"
] | Get HVCS helper class
:raises ImproperConfigurationError: if the hvcs option provided is not valid | [
"Get",
"HVCS",
"helper",
"class"
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/hvcs.py#L121-L131 | train |
relekang/python-semantic-release | semantic_release/hvcs.py | check_build_status | def check_build_status(owner: str, repository: str, ref: str) -> bool:
"""
Checks the build status of a commit on the api from your hosted version control provider.
:param owner: The owner of the repository
:param repository: The repository name
:param ref: Commit or branch reference
:return: A boolean with the build status
"""
debug('check_build_status')
return get_hvcs().check_build_status(owner, repository, ref) | python | def check_build_status(owner: str, repository: str, ref: str) -> bool:
"""
Checks the build status of a commit on the api from your hosted version control provider.
:param owner: The owner of the repository
:param repository: The repository name
:param ref: Commit or branch reference
:return: A boolean with the build status
"""
debug('check_build_status')
return get_hvcs().check_build_status(owner, repository, ref) | [
"def",
"check_build_status",
"(",
"owner",
":",
"str",
",",
"repository",
":",
"str",
",",
"ref",
":",
"str",
")",
"->",
"bool",
":",
"debug",
"(",
"'check_build_status'",
")",
"return",
"get_hvcs",
"(",
")",
".",
"check_build_status",
"(",
"owner",
",",
"repository",
",",
"ref",
")"
] | Checks the build status of a commit on the api from your hosted version control provider.
:param owner: The owner of the repository
:param repository: The repository name
:param ref: Commit or branch reference
:return: A boolean with the build status | [
"Checks",
"the",
"build",
"status",
"of",
"a",
"commit",
"on",
"the",
"api",
"from",
"your",
"hosted",
"version",
"control",
"provider",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/hvcs.py#L134-L144 | train |
relekang/python-semantic-release | semantic_release/hvcs.py | post_changelog | def post_changelog(owner: str, repository: str, version: str, changelog: str) -> Tuple[bool, dict]:
"""
Posts the changelog to the current hvcs release API
:param owner: The owner of the repository
:param repository: The repository name
:param version: A string with the new version
:param changelog: A string with the changelog in correct format
:return: a tuple with success status and payload from hvcs
"""
debug('post_changelog(owner={}, repository={}, version={})'.format(owner, repository, version))
return get_hvcs().post_release_changelog(owner, repository, version, changelog) | python | def post_changelog(owner: str, repository: str, version: str, changelog: str) -> Tuple[bool, dict]:
"""
Posts the changelog to the current hvcs release API
:param owner: The owner of the repository
:param repository: The repository name
:param version: A string with the new version
:param changelog: A string with the changelog in correct format
:return: a tuple with success status and payload from hvcs
"""
debug('post_changelog(owner={}, repository={}, version={})'.format(owner, repository, version))
return get_hvcs().post_release_changelog(owner, repository, version, changelog) | [
"def",
"post_changelog",
"(",
"owner",
":",
"str",
",",
"repository",
":",
"str",
",",
"version",
":",
"str",
",",
"changelog",
":",
"str",
")",
"->",
"Tuple",
"[",
"bool",
",",
"dict",
"]",
":",
"debug",
"(",
"'post_changelog(owner={}, repository={}, version={})'",
".",
"format",
"(",
"owner",
",",
"repository",
",",
"version",
")",
")",
"return",
"get_hvcs",
"(",
")",
".",
"post_release_changelog",
"(",
"owner",
",",
"repository",
",",
"version",
",",
"changelog",
")"
] | Posts the changelog to the current hvcs release API
:param owner: The owner of the repository
:param repository: The repository name
:param version: A string with the new version
:param changelog: A string with the changelog in correct format
:return: a tuple with success status and payload from hvcs | [
"Posts",
"the",
"changelog",
"to",
"the",
"current",
"hvcs",
"release",
"API"
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/hvcs.py#L147-L158 | train |
relekang/python-semantic-release | semantic_release/cli.py | version | def version(**kwargs):
"""
Detects the new version according to git log and semver. Writes the new version
number and commits it, unless the noop-option is True.
"""
retry = kwargs.get("retry")
if retry:
click.echo('Retrying publication of the same version...')
else:
click.echo('Creating new version..')
try:
current_version = get_current_version()
except GitError as e:
click.echo(click.style(str(e), 'red'), err=True)
return False
click.echo('Current version: {0}'.format(current_version))
level_bump = evaluate_version_bump(current_version, kwargs['force_level'])
new_version = get_new_version(current_version, level_bump)
if new_version == current_version and not retry:
click.echo(click.style('No release will be made.', fg='yellow'))
return False
if kwargs['noop'] is True:
click.echo('{0} Should have bumped from {1} to {2}.'.format(
click.style('No operation mode.', fg='yellow'),
current_version,
new_version
))
return False
if config.getboolean('semantic_release', 'check_build_status'):
click.echo('Checking build status..')
owner, name = get_repository_owner_and_name()
if not check_build_status(owner, name, get_current_head_hash()):
click.echo(click.style('The build has failed', 'red'))
return False
click.echo(click.style('The build was a success, continuing the release', 'green'))
if retry:
# No need to make changes to the repo, we're just retrying.
return True
if config.get('semantic_release', 'version_source') == 'commit':
set_new_version(new_version)
commit_new_version(new_version)
tag_new_version(new_version)
click.echo('Bumping with a {0} version to {1}.'.format(level_bump, new_version))
return True | python | def version(**kwargs):
"""
Detects the new version according to git log and semver. Writes the new version
number and commits it, unless the noop-option is True.
"""
retry = kwargs.get("retry")
if retry:
click.echo('Retrying publication of the same version...')
else:
click.echo('Creating new version..')
try:
current_version = get_current_version()
except GitError as e:
click.echo(click.style(str(e), 'red'), err=True)
return False
click.echo('Current version: {0}'.format(current_version))
level_bump = evaluate_version_bump(current_version, kwargs['force_level'])
new_version = get_new_version(current_version, level_bump)
if new_version == current_version and not retry:
click.echo(click.style('No release will be made.', fg='yellow'))
return False
if kwargs['noop'] is True:
click.echo('{0} Should have bumped from {1} to {2}.'.format(
click.style('No operation mode.', fg='yellow'),
current_version,
new_version
))
return False
if config.getboolean('semantic_release', 'check_build_status'):
click.echo('Checking build status..')
owner, name = get_repository_owner_and_name()
if not check_build_status(owner, name, get_current_head_hash()):
click.echo(click.style('The build has failed', 'red'))
return False
click.echo(click.style('The build was a success, continuing the release', 'green'))
if retry:
# No need to make changes to the repo, we're just retrying.
return True
if config.get('semantic_release', 'version_source') == 'commit':
set_new_version(new_version)
commit_new_version(new_version)
tag_new_version(new_version)
click.echo('Bumping with a {0} version to {1}.'.format(level_bump, new_version))
return True | [
"def",
"version",
"(",
"*",
"*",
"kwargs",
")",
":",
"retry",
"=",
"kwargs",
".",
"get",
"(",
"\"retry\"",
")",
"if",
"retry",
":",
"click",
".",
"echo",
"(",
"'Retrying publication of the same version...'",
")",
"else",
":",
"click",
".",
"echo",
"(",
"'Creating new version..'",
")",
"try",
":",
"current_version",
"=",
"get_current_version",
"(",
")",
"except",
"GitError",
"as",
"e",
":",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"str",
"(",
"e",
")",
",",
"'red'",
")",
",",
"err",
"=",
"True",
")",
"return",
"False",
"click",
".",
"echo",
"(",
"'Current version: {0}'",
".",
"format",
"(",
"current_version",
")",
")",
"level_bump",
"=",
"evaluate_version_bump",
"(",
"current_version",
",",
"kwargs",
"[",
"'force_level'",
"]",
")",
"new_version",
"=",
"get_new_version",
"(",
"current_version",
",",
"level_bump",
")",
"if",
"new_version",
"==",
"current_version",
"and",
"not",
"retry",
":",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"'No release will be made.'",
",",
"fg",
"=",
"'yellow'",
")",
")",
"return",
"False",
"if",
"kwargs",
"[",
"'noop'",
"]",
"is",
"True",
":",
"click",
".",
"echo",
"(",
"'{0} Should have bumped from {1} to {2}.'",
".",
"format",
"(",
"click",
".",
"style",
"(",
"'No operation mode.'",
",",
"fg",
"=",
"'yellow'",
")",
",",
"current_version",
",",
"new_version",
")",
")",
"return",
"False",
"if",
"config",
".",
"getboolean",
"(",
"'semantic_release'",
",",
"'check_build_status'",
")",
":",
"click",
".",
"echo",
"(",
"'Checking build status..'",
")",
"owner",
",",
"name",
"=",
"get_repository_owner_and_name",
"(",
")",
"if",
"not",
"check_build_status",
"(",
"owner",
",",
"name",
",",
"get_current_head_hash",
"(",
")",
")",
":",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"'The build has failed'",
",",
"'red'",
")",
")",
"return",
"False",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"'The build was a success, continuing the release'",
",",
"'green'",
")",
")",
"if",
"retry",
":",
"# No need to make changes to the repo, we're just retrying.",
"return",
"True",
"if",
"config",
".",
"get",
"(",
"'semantic_release'",
",",
"'version_source'",
")",
"==",
"'commit'",
":",
"set_new_version",
"(",
"new_version",
")",
"commit_new_version",
"(",
"new_version",
")",
"tag_new_version",
"(",
"new_version",
")",
"click",
".",
"echo",
"(",
"'Bumping with a {0} version to {1}.'",
".",
"format",
"(",
"level_bump",
",",
"new_version",
")",
")",
"return",
"True"
] | Detects the new version according to git log and semver. Writes the new version
number and commits it, unless the noop-option is True. | [
"Detects",
"the",
"new",
"version",
"according",
"to",
"git",
"log",
"and",
"semver",
".",
"Writes",
"the",
"new",
"version",
"number",
"and",
"commits",
"it",
"unless",
"the",
"noop",
"-",
"option",
"is",
"True",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/cli.py#L43-L93 | train |
relekang/python-semantic-release | semantic_release/cli.py | publish | def publish(**kwargs):
"""
Runs the version task before pushing to git and uploading to pypi.
"""
current_version = get_current_version()
click.echo('Current version: {0}'.format(current_version))
retry = kwargs.get("retry")
debug('publish: retry=', retry)
if retry:
# The "new" version will actually be the current version, and the
# "current" version will be the previous version.
new_version = current_version
current_version = get_previous_version(current_version)
else:
level_bump = evaluate_version_bump(current_version, kwargs['force_level'])
new_version = get_new_version(current_version, level_bump)
owner, name = get_repository_owner_and_name()
ci_checks.check('master')
checkout('master')
if version(**kwargs):
push_new_version(
gh_token=os.environ.get('GH_TOKEN'),
owner=owner,
name=name
)
if config.getboolean('semantic_release', 'upload_to_pypi'):
upload_to_pypi(
username=os.environ.get('PYPI_USERNAME'),
password=os.environ.get('PYPI_PASSWORD'),
# We are retrying, so we don't want errors for files that are already on PyPI.
skip_existing=retry,
)
if check_token():
click.echo('Updating changelog')
try:
log = generate_changelog(current_version, new_version)
post_changelog(
owner,
name,
new_version,
markdown_changelog(new_version, log, header=False)
)
except GitError:
click.echo(click.style('Posting changelog failed.', 'red'), err=True)
else:
click.echo(
click.style('Missing token: cannot post changelog', 'red'), err=True)
click.echo(click.style('New release published', 'green'))
else:
click.echo('Version failed, no release will be published.', err=True) | python | def publish(**kwargs):
"""
Runs the version task before pushing to git and uploading to pypi.
"""
current_version = get_current_version()
click.echo('Current version: {0}'.format(current_version))
retry = kwargs.get("retry")
debug('publish: retry=', retry)
if retry:
# The "new" version will actually be the current version, and the
# "current" version will be the previous version.
new_version = current_version
current_version = get_previous_version(current_version)
else:
level_bump = evaluate_version_bump(current_version, kwargs['force_level'])
new_version = get_new_version(current_version, level_bump)
owner, name = get_repository_owner_and_name()
ci_checks.check('master')
checkout('master')
if version(**kwargs):
push_new_version(
gh_token=os.environ.get('GH_TOKEN'),
owner=owner,
name=name
)
if config.getboolean('semantic_release', 'upload_to_pypi'):
upload_to_pypi(
username=os.environ.get('PYPI_USERNAME'),
password=os.environ.get('PYPI_PASSWORD'),
# We are retrying, so we don't want errors for files that are already on PyPI.
skip_existing=retry,
)
if check_token():
click.echo('Updating changelog')
try:
log = generate_changelog(current_version, new_version)
post_changelog(
owner,
name,
new_version,
markdown_changelog(new_version, log, header=False)
)
except GitError:
click.echo(click.style('Posting changelog failed.', 'red'), err=True)
else:
click.echo(
click.style('Missing token: cannot post changelog', 'red'), err=True)
click.echo(click.style('New release published', 'green'))
else:
click.echo('Version failed, no release will be published.', err=True) | [
"def",
"publish",
"(",
"*",
"*",
"kwargs",
")",
":",
"current_version",
"=",
"get_current_version",
"(",
")",
"click",
".",
"echo",
"(",
"'Current version: {0}'",
".",
"format",
"(",
"current_version",
")",
")",
"retry",
"=",
"kwargs",
".",
"get",
"(",
"\"retry\"",
")",
"debug",
"(",
"'publish: retry='",
",",
"retry",
")",
"if",
"retry",
":",
"# The \"new\" version will actually be the current version, and the",
"# \"current\" version will be the previous version.",
"new_version",
"=",
"current_version",
"current_version",
"=",
"get_previous_version",
"(",
"current_version",
")",
"else",
":",
"level_bump",
"=",
"evaluate_version_bump",
"(",
"current_version",
",",
"kwargs",
"[",
"'force_level'",
"]",
")",
"new_version",
"=",
"get_new_version",
"(",
"current_version",
",",
"level_bump",
")",
"owner",
",",
"name",
"=",
"get_repository_owner_and_name",
"(",
")",
"ci_checks",
".",
"check",
"(",
"'master'",
")",
"checkout",
"(",
"'master'",
")",
"if",
"version",
"(",
"*",
"*",
"kwargs",
")",
":",
"push_new_version",
"(",
"gh_token",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'GH_TOKEN'",
")",
",",
"owner",
"=",
"owner",
",",
"name",
"=",
"name",
")",
"if",
"config",
".",
"getboolean",
"(",
"'semantic_release'",
",",
"'upload_to_pypi'",
")",
":",
"upload_to_pypi",
"(",
"username",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PYPI_USERNAME'",
")",
",",
"password",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PYPI_PASSWORD'",
")",
",",
"# We are retrying, so we don't want errors for files that are already on PyPI.",
"skip_existing",
"=",
"retry",
",",
")",
"if",
"check_token",
"(",
")",
":",
"click",
".",
"echo",
"(",
"'Updating changelog'",
")",
"try",
":",
"log",
"=",
"generate_changelog",
"(",
"current_version",
",",
"new_version",
")",
"post_changelog",
"(",
"owner",
",",
"name",
",",
"new_version",
",",
"markdown_changelog",
"(",
"new_version",
",",
"log",
",",
"header",
"=",
"False",
")",
")",
"except",
"GitError",
":",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"'Posting changelog failed.'",
",",
"'red'",
")",
",",
"err",
"=",
"True",
")",
"else",
":",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"'Missing token: cannot post changelog'",
",",
"'red'",
")",
",",
"err",
"=",
"True",
")",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"'New release published'",
",",
"'green'",
")",
")",
"else",
":",
"click",
".",
"echo",
"(",
"'Version failed, no release will be published.'",
",",
"err",
"=",
"True",
")"
] | Runs the version task before pushing to git and uploading to pypi. | [
"Runs",
"the",
"version",
"task",
"before",
"pushing",
"to",
"git",
"and",
"uploading",
"to",
"pypi",
"."
] | 76123f410180599a19e7c48da413880185bbea20 | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/cli.py#L132-L188 | train |
aljosa/django-tinymce | tinymce/views.py | flatpages_link_list | def flatpages_link_list(request):
"""
Returns a HttpResponse whose content is a Javascript file representing a
list of links to flatpages.
"""
from django.contrib.flatpages.models import FlatPage
link_list = [(page.title, page.url) for page in FlatPage.objects.all()]
return render_to_link_list(link_list) | python | def flatpages_link_list(request):
"""
Returns a HttpResponse whose content is a Javascript file representing a
list of links to flatpages.
"""
from django.contrib.flatpages.models import FlatPage
link_list = [(page.title, page.url) for page in FlatPage.objects.all()]
return render_to_link_list(link_list) | [
"def",
"flatpages_link_list",
"(",
"request",
")",
":",
"from",
"django",
".",
"contrib",
".",
"flatpages",
".",
"models",
"import",
"FlatPage",
"link_list",
"=",
"[",
"(",
"page",
".",
"title",
",",
"page",
".",
"url",
")",
"for",
"page",
"in",
"FlatPage",
".",
"objects",
".",
"all",
"(",
")",
"]",
"return",
"render_to_link_list",
"(",
"link_list",
")"
] | Returns a HttpResponse whose content is a Javascript file representing a
list of links to flatpages. | [
"Returns",
"a",
"HttpResponse",
"whose",
"content",
"is",
"a",
"Javascript",
"file",
"representing",
"a",
"list",
"of",
"links",
"to",
"flatpages",
"."
] | a509fdbc6c623ddac6552199da89712c0f026c91 | https://github.com/aljosa/django-tinymce/blob/a509fdbc6c623ddac6552199da89712c0f026c91/tinymce/views.py#L72-L79 | train |
aio-libs/aiomonitor | aiomonitor/monitor.py | Monitor._interactive_loop | def _interactive_loop(self, sin: IO[str], sout: IO[str]) -> None:
"""Main interactive loop of the monitor"""
self._sin = sin
self._sout = sout
tasknum = len(all_tasks(loop=self._loop))
s = '' if tasknum == 1 else 's'
self._sout.write(self.intro.format(tasknum=tasknum, s=s))
try:
while not self._closing.is_set():
self._sout.write(self.prompt)
self._sout.flush()
try:
user_input = sin.readline().strip()
except Exception as e:
msg = 'Could not read from user input due to:\n{}\n'
log.exception(msg)
self._sout.write(msg.format(repr(e)))
self._sout.flush()
else:
try:
self._command_dispatch(user_input)
except Exception as e:
msg = 'Unexpected Exception during command execution:\n{}\n' # noqa
log.exception(msg)
self._sout.write(msg.format(repr(e)))
self._sout.flush()
finally:
self._sin = None # type: ignore
self._sout = None | python | def _interactive_loop(self, sin: IO[str], sout: IO[str]) -> None:
"""Main interactive loop of the monitor"""
self._sin = sin
self._sout = sout
tasknum = len(all_tasks(loop=self._loop))
s = '' if tasknum == 1 else 's'
self._sout.write(self.intro.format(tasknum=tasknum, s=s))
try:
while not self._closing.is_set():
self._sout.write(self.prompt)
self._sout.flush()
try:
user_input = sin.readline().strip()
except Exception as e:
msg = 'Could not read from user input due to:\n{}\n'
log.exception(msg)
self._sout.write(msg.format(repr(e)))
self._sout.flush()
else:
try:
self._command_dispatch(user_input)
except Exception as e:
msg = 'Unexpected Exception during command execution:\n{}\n' # noqa
log.exception(msg)
self._sout.write(msg.format(repr(e)))
self._sout.flush()
finally:
self._sin = None # type: ignore
self._sout = None | [
"def",
"_interactive_loop",
"(",
"self",
",",
"sin",
":",
"IO",
"[",
"str",
"]",
",",
"sout",
":",
"IO",
"[",
"str",
"]",
")",
"->",
"None",
":",
"self",
".",
"_sin",
"=",
"sin",
"self",
".",
"_sout",
"=",
"sout",
"tasknum",
"=",
"len",
"(",
"all_tasks",
"(",
"loop",
"=",
"self",
".",
"_loop",
")",
")",
"s",
"=",
"''",
"if",
"tasknum",
"==",
"1",
"else",
"'s'",
"self",
".",
"_sout",
".",
"write",
"(",
"self",
".",
"intro",
".",
"format",
"(",
"tasknum",
"=",
"tasknum",
",",
"s",
"=",
"s",
")",
")",
"try",
":",
"while",
"not",
"self",
".",
"_closing",
".",
"is_set",
"(",
")",
":",
"self",
".",
"_sout",
".",
"write",
"(",
"self",
".",
"prompt",
")",
"self",
".",
"_sout",
".",
"flush",
"(",
")",
"try",
":",
"user_input",
"=",
"sin",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"msg",
"=",
"'Could not read from user input due to:\\n{}\\n'",
"log",
".",
"exception",
"(",
"msg",
")",
"self",
".",
"_sout",
".",
"write",
"(",
"msg",
".",
"format",
"(",
"repr",
"(",
"e",
")",
")",
")",
"self",
".",
"_sout",
".",
"flush",
"(",
")",
"else",
":",
"try",
":",
"self",
".",
"_command_dispatch",
"(",
"user_input",
")",
"except",
"Exception",
"as",
"e",
":",
"msg",
"=",
"'Unexpected Exception during command execution:\\n{}\\n'",
"# noqa",
"log",
".",
"exception",
"(",
"msg",
")",
"self",
".",
"_sout",
".",
"write",
"(",
"msg",
".",
"format",
"(",
"repr",
"(",
"e",
")",
")",
")",
"self",
".",
"_sout",
".",
"flush",
"(",
")",
"finally",
":",
"self",
".",
"_sin",
"=",
"None",
"# type: ignore",
"self",
".",
"_sout",
"=",
"None"
] | Main interactive loop of the monitor | [
"Main",
"interactive",
"loop",
"of",
"the",
"monitor"
] | fe5f9caa0b117861afef13b64bce5dce3a415b80 | https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L156-L184 | train |
aio-libs/aiomonitor | aiomonitor/monitor.py | Monitor.do_help | def do_help(self, *cmd_names: str) -> None:
"""Show help for command name
Any number of command names may be given to help, and the long help
text for all of them will be shown.
"""
def _h(cmd: str, template: str) -> None:
try:
func = getattr(self, cmd)
except AttributeError:
self._sout.write('No such command: {}\n'.format(cmd))
else:
doc = func.__doc__ if func.__doc__ else ''
doc_firstline = doc.split('\n', maxsplit=1)[0]
arg_list = ' '.join(
p for p in inspect.signature(func).parameters)
self._sout.write(
template.format(
cmd_name=cmd[len(self._cmd_prefix):],
arg_list=arg_list,
cmd_arg_sep=' ' if arg_list else '',
doc=doc,
doc_firstline=doc_firstline
) + '\n'
)
if not cmd_names:
cmds = sorted(
c.method_name for c in self._filter_cmds(with_alts=False)
)
self._sout.write('Available Commands are:\n\n')
for cmd in cmds:
_h(cmd, self.help_short_template)
else:
for cmd in cmd_names:
_h(self._cmd_prefix + cmd, self.help_template) | python | def do_help(self, *cmd_names: str) -> None:
"""Show help for command name
Any number of command names may be given to help, and the long help
text for all of them will be shown.
"""
def _h(cmd: str, template: str) -> None:
try:
func = getattr(self, cmd)
except AttributeError:
self._sout.write('No such command: {}\n'.format(cmd))
else:
doc = func.__doc__ if func.__doc__ else ''
doc_firstline = doc.split('\n', maxsplit=1)[0]
arg_list = ' '.join(
p for p in inspect.signature(func).parameters)
self._sout.write(
template.format(
cmd_name=cmd[len(self._cmd_prefix):],
arg_list=arg_list,
cmd_arg_sep=' ' if arg_list else '',
doc=doc,
doc_firstline=doc_firstline
) + '\n'
)
if not cmd_names:
cmds = sorted(
c.method_name for c in self._filter_cmds(with_alts=False)
)
self._sout.write('Available Commands are:\n\n')
for cmd in cmds:
_h(cmd, self.help_short_template)
else:
for cmd in cmd_names:
_h(self._cmd_prefix + cmd, self.help_template) | [
"def",
"do_help",
"(",
"self",
",",
"*",
"cmd_names",
":",
"str",
")",
"->",
"None",
":",
"def",
"_h",
"(",
"cmd",
":",
"str",
",",
"template",
":",
"str",
")",
"->",
"None",
":",
"try",
":",
"func",
"=",
"getattr",
"(",
"self",
",",
"cmd",
")",
"except",
"AttributeError",
":",
"self",
".",
"_sout",
".",
"write",
"(",
"'No such command: {}\\n'",
".",
"format",
"(",
"cmd",
")",
")",
"else",
":",
"doc",
"=",
"func",
".",
"__doc__",
"if",
"func",
".",
"__doc__",
"else",
"''",
"doc_firstline",
"=",
"doc",
".",
"split",
"(",
"'\\n'",
",",
"maxsplit",
"=",
"1",
")",
"[",
"0",
"]",
"arg_list",
"=",
"' '",
".",
"join",
"(",
"p",
"for",
"p",
"in",
"inspect",
".",
"signature",
"(",
"func",
")",
".",
"parameters",
")",
"self",
".",
"_sout",
".",
"write",
"(",
"template",
".",
"format",
"(",
"cmd_name",
"=",
"cmd",
"[",
"len",
"(",
"self",
".",
"_cmd_prefix",
")",
":",
"]",
",",
"arg_list",
"=",
"arg_list",
",",
"cmd_arg_sep",
"=",
"' '",
"if",
"arg_list",
"else",
"''",
",",
"doc",
"=",
"doc",
",",
"doc_firstline",
"=",
"doc_firstline",
")",
"+",
"'\\n'",
")",
"if",
"not",
"cmd_names",
":",
"cmds",
"=",
"sorted",
"(",
"c",
".",
"method_name",
"for",
"c",
"in",
"self",
".",
"_filter_cmds",
"(",
"with_alts",
"=",
"False",
")",
")",
"self",
".",
"_sout",
".",
"write",
"(",
"'Available Commands are:\\n\\n'",
")",
"for",
"cmd",
"in",
"cmds",
":",
"_h",
"(",
"cmd",
",",
"self",
".",
"help_short_template",
")",
"else",
":",
"for",
"cmd",
"in",
"cmd_names",
":",
"_h",
"(",
"self",
".",
"_cmd_prefix",
"+",
"cmd",
",",
"self",
".",
"help_template",
")"
] | Show help for command name
Any number of command names may be given to help, and the long help
text for all of them will be shown. | [
"Show",
"help",
"for",
"command",
"name"
] | fe5f9caa0b117861afef13b64bce5dce3a415b80 | https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L299-L334 | train |
aio-libs/aiomonitor | aiomonitor/monitor.py | Monitor.do_ps | def do_ps(self) -> None:
"""Show task table"""
headers = ('Task ID', 'State', 'Task')
table_data = [headers]
for task in sorted(all_tasks(loop=self._loop), key=id):
taskid = str(id(task))
if task:
t = '\n'.join(wrap(str(task), 80))
table_data.append((taskid, task._state, t))
table = AsciiTable(table_data)
self._sout.write(table.table)
self._sout.write('\n')
self._sout.flush() | python | def do_ps(self) -> None:
"""Show task table"""
headers = ('Task ID', 'State', 'Task')
table_data = [headers]
for task in sorted(all_tasks(loop=self._loop), key=id):
taskid = str(id(task))
if task:
t = '\n'.join(wrap(str(task), 80))
table_data.append((taskid, task._state, t))
table = AsciiTable(table_data)
self._sout.write(table.table)
self._sout.write('\n')
self._sout.flush() | [
"def",
"do_ps",
"(",
"self",
")",
"->",
"None",
":",
"headers",
"=",
"(",
"'Task ID'",
",",
"'State'",
",",
"'Task'",
")",
"table_data",
"=",
"[",
"headers",
"]",
"for",
"task",
"in",
"sorted",
"(",
"all_tasks",
"(",
"loop",
"=",
"self",
".",
"_loop",
")",
",",
"key",
"=",
"id",
")",
":",
"taskid",
"=",
"str",
"(",
"id",
"(",
"task",
")",
")",
"if",
"task",
":",
"t",
"=",
"'\\n'",
".",
"join",
"(",
"wrap",
"(",
"str",
"(",
"task",
")",
",",
"80",
")",
")",
"table_data",
".",
"append",
"(",
"(",
"taskid",
",",
"task",
".",
"_state",
",",
"t",
")",
")",
"table",
"=",
"AsciiTable",
"(",
"table_data",
")",
"self",
".",
"_sout",
".",
"write",
"(",
"table",
".",
"table",
")",
"self",
".",
"_sout",
".",
"write",
"(",
"'\\n'",
")",
"self",
".",
"_sout",
".",
"flush",
"(",
")"
] | Show task table | [
"Show",
"task",
"table"
] | fe5f9caa0b117861afef13b64bce5dce3a415b80 | https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L337-L349 | train |
aio-libs/aiomonitor | aiomonitor/monitor.py | Monitor.do_where | def do_where(self, taskid: int) -> None:
"""Show stack frames for a task"""
task = task_by_id(taskid, self._loop)
if task:
self._sout.write(_format_stack(task))
self._sout.write('\n')
else:
self._sout.write('No task %d\n' % taskid) | python | def do_where(self, taskid: int) -> None:
"""Show stack frames for a task"""
task = task_by_id(taskid, self._loop)
if task:
self._sout.write(_format_stack(task))
self._sout.write('\n')
else:
self._sout.write('No task %d\n' % taskid) | [
"def",
"do_where",
"(",
"self",
",",
"taskid",
":",
"int",
")",
"->",
"None",
":",
"task",
"=",
"task_by_id",
"(",
"taskid",
",",
"self",
".",
"_loop",
")",
"if",
"task",
":",
"self",
".",
"_sout",
".",
"write",
"(",
"_format_stack",
"(",
"task",
")",
")",
"self",
".",
"_sout",
".",
"write",
"(",
"'\\n'",
")",
"else",
":",
"self",
".",
"_sout",
".",
"write",
"(",
"'No task %d\\n'",
"%",
"taskid",
")"
] | Show stack frames for a task | [
"Show",
"stack",
"frames",
"for",
"a",
"task"
] | fe5f9caa0b117861afef13b64bce5dce3a415b80 | https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L352-L359 | train |
aio-libs/aiomonitor | aiomonitor/monitor.py | Monitor.do_signal | def do_signal(self, signame: str) -> None:
"""Send a Unix signal"""
if hasattr(signal, signame):
os.kill(os.getpid(), getattr(signal, signame))
else:
self._sout.write('Unknown signal %s\n' % signame) | python | def do_signal(self, signame: str) -> None:
"""Send a Unix signal"""
if hasattr(signal, signame):
os.kill(os.getpid(), getattr(signal, signame))
else:
self._sout.write('Unknown signal %s\n' % signame) | [
"def",
"do_signal",
"(",
"self",
",",
"signame",
":",
"str",
")",
"->",
"None",
":",
"if",
"hasattr",
"(",
"signal",
",",
"signame",
")",
":",
"os",
".",
"kill",
"(",
"os",
".",
"getpid",
"(",
")",
",",
"getattr",
"(",
"signal",
",",
"signame",
")",
")",
"else",
":",
"self",
".",
"_sout",
".",
"write",
"(",
"'Unknown signal %s\\n'",
"%",
"signame",
")"
] | Send a Unix signal | [
"Send",
"a",
"Unix",
"signal"
] | fe5f9caa0b117861afef13b64bce5dce3a415b80 | https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L361-L366 | train |
aio-libs/aiomonitor | aiomonitor/monitor.py | Monitor.do_stacktrace | def do_stacktrace(self) -> None:
"""Print a stack trace from the event loop thread"""
frame = sys._current_frames()[self._event_loop_thread_id]
traceback.print_stack(frame, file=self._sout) | python | def do_stacktrace(self) -> None:
"""Print a stack trace from the event loop thread"""
frame = sys._current_frames()[self._event_loop_thread_id]
traceback.print_stack(frame, file=self._sout) | [
"def",
"do_stacktrace",
"(",
"self",
")",
"->",
"None",
":",
"frame",
"=",
"sys",
".",
"_current_frames",
"(",
")",
"[",
"self",
".",
"_event_loop_thread_id",
"]",
"traceback",
".",
"print_stack",
"(",
"frame",
",",
"file",
"=",
"self",
".",
"_sout",
")"
] | Print a stack trace from the event loop thread | [
"Print",
"a",
"stack",
"trace",
"from",
"the",
"event",
"loop",
"thread"
] | fe5f9caa0b117861afef13b64bce5dce3a415b80 | https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L369-L372 | train |
aio-libs/aiomonitor | aiomonitor/monitor.py | Monitor.do_cancel | def do_cancel(self, taskid: int) -> None:
"""Cancel an indicated task"""
task = task_by_id(taskid, self._loop)
if task:
fut = asyncio.run_coroutine_threadsafe(
cancel_task(task), loop=self._loop)
fut.result(timeout=3)
self._sout.write('Cancel task %d\n' % taskid)
else:
self._sout.write('No task %d\n' % taskid) | python | def do_cancel(self, taskid: int) -> None:
"""Cancel an indicated task"""
task = task_by_id(taskid, self._loop)
if task:
fut = asyncio.run_coroutine_threadsafe(
cancel_task(task), loop=self._loop)
fut.result(timeout=3)
self._sout.write('Cancel task %d\n' % taskid)
else:
self._sout.write('No task %d\n' % taskid) | [
"def",
"do_cancel",
"(",
"self",
",",
"taskid",
":",
"int",
")",
"->",
"None",
":",
"task",
"=",
"task_by_id",
"(",
"taskid",
",",
"self",
".",
"_loop",
")",
"if",
"task",
":",
"fut",
"=",
"asyncio",
".",
"run_coroutine_threadsafe",
"(",
"cancel_task",
"(",
"task",
")",
",",
"loop",
"=",
"self",
".",
"_loop",
")",
"fut",
".",
"result",
"(",
"timeout",
"=",
"3",
")",
"self",
".",
"_sout",
".",
"write",
"(",
"'Cancel task %d\\n'",
"%",
"taskid",
")",
"else",
":",
"self",
".",
"_sout",
".",
"write",
"(",
"'No task %d\\n'",
"%",
"taskid",
")"
] | Cancel an indicated task | [
"Cancel",
"an",
"indicated",
"task"
] | fe5f9caa0b117861afef13b64bce5dce3a415b80 | https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L374-L383 | train |
aio-libs/aiomonitor | aiomonitor/monitor.py | Monitor.do_console | def do_console(self) -> None:
"""Switch to async Python REPL"""
if not self._console_enabled:
self._sout.write('Python console disabled for this sessiong\n')
self._sout.flush()
return
h, p = self._host, self._console_port
log.info('Starting console at %s:%d', h, p)
fut = init_console_server(
self._host, self._console_port, self._locals, self._loop)
server = fut.result(timeout=3)
try:
console_proxy(
self._sin, self._sout, self._host, self._console_port)
finally:
coro = close_server(server)
close_fut = asyncio.run_coroutine_threadsafe(coro, loop=self._loop)
close_fut.result(timeout=15) | python | def do_console(self) -> None:
"""Switch to async Python REPL"""
if not self._console_enabled:
self._sout.write('Python console disabled for this sessiong\n')
self._sout.flush()
return
h, p = self._host, self._console_port
log.info('Starting console at %s:%d', h, p)
fut = init_console_server(
self._host, self._console_port, self._locals, self._loop)
server = fut.result(timeout=3)
try:
console_proxy(
self._sin, self._sout, self._host, self._console_port)
finally:
coro = close_server(server)
close_fut = asyncio.run_coroutine_threadsafe(coro, loop=self._loop)
close_fut.result(timeout=15) | [
"def",
"do_console",
"(",
"self",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"_console_enabled",
":",
"self",
".",
"_sout",
".",
"write",
"(",
"'Python console disabled for this sessiong\\n'",
")",
"self",
".",
"_sout",
".",
"flush",
"(",
")",
"return",
"h",
",",
"p",
"=",
"self",
".",
"_host",
",",
"self",
".",
"_console_port",
"log",
".",
"info",
"(",
"'Starting console at %s:%d'",
",",
"h",
",",
"p",
")",
"fut",
"=",
"init_console_server",
"(",
"self",
".",
"_host",
",",
"self",
".",
"_console_port",
",",
"self",
".",
"_locals",
",",
"self",
".",
"_loop",
")",
"server",
"=",
"fut",
".",
"result",
"(",
"timeout",
"=",
"3",
")",
"try",
":",
"console_proxy",
"(",
"self",
".",
"_sin",
",",
"self",
".",
"_sout",
",",
"self",
".",
"_host",
",",
"self",
".",
"_console_port",
")",
"finally",
":",
"coro",
"=",
"close_server",
"(",
"server",
")",
"close_fut",
"=",
"asyncio",
".",
"run_coroutine_threadsafe",
"(",
"coro",
",",
"loop",
"=",
"self",
".",
"_loop",
")",
"close_fut",
".",
"result",
"(",
"timeout",
"=",
"15",
")"
] | Switch to async Python REPL | [
"Switch",
"to",
"async",
"Python",
"REPL"
] | fe5f9caa0b117861afef13b64bce5dce3a415b80 | https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L391-L409 | train |
aio-libs/aiomonitor | aiomonitor/utils.py | alt_names | def alt_names(names: str) -> Callable[..., Any]:
"""Add alternative names to you custom commands.
`names` is a single string with a space separated list of aliases for the
decorated command.
"""
names_split = names.split()
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
func.alt_names = names_split # type: ignore
return func
return decorator | python | def alt_names(names: str) -> Callable[..., Any]:
"""Add alternative names to you custom commands.
`names` is a single string with a space separated list of aliases for the
decorated command.
"""
names_split = names.split()
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
func.alt_names = names_split # type: ignore
return func
return decorator | [
"def",
"alt_names",
"(",
"names",
":",
"str",
")",
"->",
"Callable",
"[",
"...",
",",
"Any",
"]",
":",
"names_split",
"=",
"names",
".",
"split",
"(",
")",
"def",
"decorator",
"(",
"func",
":",
"Callable",
"[",
"...",
",",
"Any",
"]",
")",
"->",
"Callable",
"[",
"...",
",",
"Any",
"]",
":",
"func",
".",
"alt_names",
"=",
"names_split",
"# type: ignore",
"return",
"func",
"return",
"decorator"
] | Add alternative names to you custom commands.
`names` is a single string with a space separated list of aliases for the
decorated command. | [
"Add",
"alternative",
"names",
"to",
"you",
"custom",
"commands",
"."
] | fe5f9caa0b117861afef13b64bce5dce3a415b80 | https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/utils.py#L115-L126 | train |
vxgmichel/aioconsole | aioconsole/events.py | set_interactive_policy | def set_interactive_policy(*, locals=None, banner=None, serve=None,
prompt_control=None):
"""Use an interactive event loop by default."""
policy = InteractiveEventLoopPolicy(
locals=locals,
banner=banner,
serve=serve,
prompt_control=prompt_control)
asyncio.set_event_loop_policy(policy) | python | def set_interactive_policy(*, locals=None, banner=None, serve=None,
prompt_control=None):
"""Use an interactive event loop by default."""
policy = InteractiveEventLoopPolicy(
locals=locals,
banner=banner,
serve=serve,
prompt_control=prompt_control)
asyncio.set_event_loop_policy(policy) | [
"def",
"set_interactive_policy",
"(",
"*",
",",
"locals",
"=",
"None",
",",
"banner",
"=",
"None",
",",
"serve",
"=",
"None",
",",
"prompt_control",
"=",
"None",
")",
":",
"policy",
"=",
"InteractiveEventLoopPolicy",
"(",
"locals",
"=",
"locals",
",",
"banner",
"=",
"banner",
",",
"serve",
"=",
"serve",
",",
"prompt_control",
"=",
"prompt_control",
")",
"asyncio",
".",
"set_event_loop_policy",
"(",
"policy",
")"
] | Use an interactive event loop by default. | [
"Use",
"an",
"interactive",
"event",
"loop",
"by",
"default",
"."
] | 8223435723d616fd4db398431d6a6182a6015e3f | https://github.com/vxgmichel/aioconsole/blob/8223435723d616fd4db398431d6a6182a6015e3f/aioconsole/events.py#L71-L79 | train |
vxgmichel/aioconsole | aioconsole/events.py | run_console | def run_console(*, locals=None, banner=None, serve=None, prompt_control=None):
"""Run the interactive event loop."""
loop = InteractiveEventLoop(
locals=locals,
banner=banner,
serve=serve,
prompt_control=prompt_control)
asyncio.set_event_loop(loop)
try:
loop.run_forever()
except KeyboardInterrupt:
pass | python | def run_console(*, locals=None, banner=None, serve=None, prompt_control=None):
"""Run the interactive event loop."""
loop = InteractiveEventLoop(
locals=locals,
banner=banner,
serve=serve,
prompt_control=prompt_control)
asyncio.set_event_loop(loop)
try:
loop.run_forever()
except KeyboardInterrupt:
pass | [
"def",
"run_console",
"(",
"*",
",",
"locals",
"=",
"None",
",",
"banner",
"=",
"None",
",",
"serve",
"=",
"None",
",",
"prompt_control",
"=",
"None",
")",
":",
"loop",
"=",
"InteractiveEventLoop",
"(",
"locals",
"=",
"locals",
",",
"banner",
"=",
"banner",
",",
"serve",
"=",
"serve",
",",
"prompt_control",
"=",
"prompt_control",
")",
"asyncio",
".",
"set_event_loop",
"(",
"loop",
")",
"try",
":",
"loop",
".",
"run_forever",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"pass"
] | Run the interactive event loop. | [
"Run",
"the",
"interactive",
"event",
"loop",
"."
] | 8223435723d616fd4db398431d6a6182a6015e3f | https://github.com/vxgmichel/aioconsole/blob/8223435723d616fd4db398431d6a6182a6015e3f/aioconsole/events.py#L82-L93 | train |
vxgmichel/aioconsole | aioconsole/execute.py | make_arg | def make_arg(key, annotation=None):
"""Make an ast function argument."""
arg = ast.arg(key, annotation)
arg.lineno, arg.col_offset = 0, 0
return arg | python | def make_arg(key, annotation=None):
"""Make an ast function argument."""
arg = ast.arg(key, annotation)
arg.lineno, arg.col_offset = 0, 0
return arg | [
"def",
"make_arg",
"(",
"key",
",",
"annotation",
"=",
"None",
")",
":",
"arg",
"=",
"ast",
".",
"arg",
"(",
"key",
",",
"annotation",
")",
"arg",
".",
"lineno",
",",
"arg",
".",
"col_offset",
"=",
"0",
",",
"0",
"return",
"arg"
] | Make an ast function argument. | [
"Make",
"an",
"ast",
"function",
"argument",
"."
] | 8223435723d616fd4db398431d6a6182a6015e3f | https://github.com/vxgmichel/aioconsole/blob/8223435723d616fd4db398431d6a6182a6015e3f/aioconsole/execute.py#L16-L20 | train |
vxgmichel/aioconsole | aioconsole/execute.py | make_coroutine_from_tree | def make_coroutine_from_tree(tree, filename="<aexec>", symbol="single",
local={}):
"""Make a coroutine from a tree structure."""
dct = {}
tree.body[0].args.args = list(map(make_arg, local))
exec(compile(tree, filename, symbol), dct)
return asyncio.coroutine(dct[CORO_NAME])(**local) | python | def make_coroutine_from_tree(tree, filename="<aexec>", symbol="single",
local={}):
"""Make a coroutine from a tree structure."""
dct = {}
tree.body[0].args.args = list(map(make_arg, local))
exec(compile(tree, filename, symbol), dct)
return asyncio.coroutine(dct[CORO_NAME])(**local) | [
"def",
"make_coroutine_from_tree",
"(",
"tree",
",",
"filename",
"=",
"\"<aexec>\"",
",",
"symbol",
"=",
"\"single\"",
",",
"local",
"=",
"{",
"}",
")",
":",
"dct",
"=",
"{",
"}",
"tree",
".",
"body",
"[",
"0",
"]",
".",
"args",
".",
"args",
"=",
"list",
"(",
"map",
"(",
"make_arg",
",",
"local",
")",
")",
"exec",
"(",
"compile",
"(",
"tree",
",",
"filename",
",",
"symbol",
")",
",",
"dct",
")",
"return",
"asyncio",
".",
"coroutine",
"(",
"dct",
"[",
"CORO_NAME",
"]",
")",
"(",
"*",
"*",
"local",
")"
] | Make a coroutine from a tree structure. | [
"Make",
"a",
"coroutine",
"from",
"a",
"tree",
"structure",
"."
] | 8223435723d616fd4db398431d6a6182a6015e3f | https://github.com/vxgmichel/aioconsole/blob/8223435723d616fd4db398431d6a6182a6015e3f/aioconsole/execute.py#L50-L56 | train |
libfuse/python-fuse | fuse.py | feature_needs | def feature_needs(*feas):
"""
Get info about the FUSE API version needed for the support of some features.
This function takes a variable number of feature patterns.
A feature pattern is either:
- an integer (directly referring to a FUSE API version number)
- a built-in feature specifier string (meaning defined by dictionary)
- a string of the form ``has_foo``, where ``foo`` is a filesystem method
(refers to the API version where the method has been introduced)
- a list/tuple of other feature patterns (matches each of its members)
- a regexp (meant to be matched against the builtins plus ``has_foo``
patterns; can also be given by a string of the from "re:*")
- a negated regexp (can be given by a string of the form "!re:*")
If called with no arguments, then the list of builtins is returned, mapped
to their meaning.
Otherwise the function returns the smallest FUSE API version number which
has all the matching features.
Builtin specifiers worth to explicit mention:
- ``stateful_files``: you want to use custom filehandles (eg. a file class).
- ``*``: you want all features.
- while ``has_foo`` makes sense for all filesystem method ``foo``, some
of these can be found among the builtins, too (the ones which can be
handled by the general rule).
specifiers like ``has_foo`` refer to requirement that the library knows of
the fs method ``foo``.
"""
fmap = {'stateful_files': 22,
'stateful_dirs': 23,
'stateful_io': ('stateful_files', 'stateful_dirs'),
'stateful_files_keep_cache': 23,
'stateful_files_direct_io': 23,
'keep_cache': ('stateful_files_keep_cache',),
'direct_io': ('stateful_files_direct_io',),
'has_opendir': ('stateful_dirs',),
'has_releasedir': ('stateful_dirs',),
'has_fsyncdir': ('stateful_dirs',),
'has_create': 25,
'has_access': 25,
'has_fgetattr': 25,
'has_ftruncate': 25,
'has_fsinit': ('has_init'),
'has_fsdestroy': ('has_destroy'),
'has_lock': 26,
'has_utimens': 26,
'has_bmap': 26,
'has_init': 23,
'has_destroy': 23,
'*': '!re:^\*$'}
if not feas:
return fmap
def resolve(args, maxva):
for fp in args:
if isinstance(fp, int):
maxva[0] = max(maxva[0], fp)
continue
if isinstance(fp, list) or isinstance(fp, tuple):
for f in fp:
yield f
continue
ma = isinstance(fp, str) and re.compile("(!\s*|)re:(.*)").match(fp)
if isinstance(fp, type(re.compile(''))) or ma:
neg = False
if ma:
mag = ma.groups()
fp = re.compile(mag[1])
neg = bool(mag[0])
for f in list(fmap.keys()) + [ 'has_' + a for a in Fuse._attrs ]:
if neg != bool(re.search(fp, f)):
yield f
continue
ma = re.compile("has_(.*)").match(fp)
if ma and ma.groups()[0] in Fuse._attrs and not fp in fmap:
yield 21
continue
yield fmap[fp]
maxva = [0]
while feas:
feas = set(resolve(feas, maxva))
return maxva[0] | python | def feature_needs(*feas):
"""
Get info about the FUSE API version needed for the support of some features.
This function takes a variable number of feature patterns.
A feature pattern is either:
- an integer (directly referring to a FUSE API version number)
- a built-in feature specifier string (meaning defined by dictionary)
- a string of the form ``has_foo``, where ``foo`` is a filesystem method
(refers to the API version where the method has been introduced)
- a list/tuple of other feature patterns (matches each of its members)
- a regexp (meant to be matched against the builtins plus ``has_foo``
patterns; can also be given by a string of the from "re:*")
- a negated regexp (can be given by a string of the form "!re:*")
If called with no arguments, then the list of builtins is returned, mapped
to their meaning.
Otherwise the function returns the smallest FUSE API version number which
has all the matching features.
Builtin specifiers worth to explicit mention:
- ``stateful_files``: you want to use custom filehandles (eg. a file class).
- ``*``: you want all features.
- while ``has_foo`` makes sense for all filesystem method ``foo``, some
of these can be found among the builtins, too (the ones which can be
handled by the general rule).
specifiers like ``has_foo`` refer to requirement that the library knows of
the fs method ``foo``.
"""
fmap = {'stateful_files': 22,
'stateful_dirs': 23,
'stateful_io': ('stateful_files', 'stateful_dirs'),
'stateful_files_keep_cache': 23,
'stateful_files_direct_io': 23,
'keep_cache': ('stateful_files_keep_cache',),
'direct_io': ('stateful_files_direct_io',),
'has_opendir': ('stateful_dirs',),
'has_releasedir': ('stateful_dirs',),
'has_fsyncdir': ('stateful_dirs',),
'has_create': 25,
'has_access': 25,
'has_fgetattr': 25,
'has_ftruncate': 25,
'has_fsinit': ('has_init'),
'has_fsdestroy': ('has_destroy'),
'has_lock': 26,
'has_utimens': 26,
'has_bmap': 26,
'has_init': 23,
'has_destroy': 23,
'*': '!re:^\*$'}
if not feas:
return fmap
def resolve(args, maxva):
for fp in args:
if isinstance(fp, int):
maxva[0] = max(maxva[0], fp)
continue
if isinstance(fp, list) or isinstance(fp, tuple):
for f in fp:
yield f
continue
ma = isinstance(fp, str) and re.compile("(!\s*|)re:(.*)").match(fp)
if isinstance(fp, type(re.compile(''))) or ma:
neg = False
if ma:
mag = ma.groups()
fp = re.compile(mag[1])
neg = bool(mag[0])
for f in list(fmap.keys()) + [ 'has_' + a for a in Fuse._attrs ]:
if neg != bool(re.search(fp, f)):
yield f
continue
ma = re.compile("has_(.*)").match(fp)
if ma and ma.groups()[0] in Fuse._attrs and not fp in fmap:
yield 21
continue
yield fmap[fp]
maxva = [0]
while feas:
feas = set(resolve(feas, maxva))
return maxva[0] | [
"def",
"feature_needs",
"(",
"*",
"feas",
")",
":",
"fmap",
"=",
"{",
"'stateful_files'",
":",
"22",
",",
"'stateful_dirs'",
":",
"23",
",",
"'stateful_io'",
":",
"(",
"'stateful_files'",
",",
"'stateful_dirs'",
")",
",",
"'stateful_files_keep_cache'",
":",
"23",
",",
"'stateful_files_direct_io'",
":",
"23",
",",
"'keep_cache'",
":",
"(",
"'stateful_files_keep_cache'",
",",
")",
",",
"'direct_io'",
":",
"(",
"'stateful_files_direct_io'",
",",
")",
",",
"'has_opendir'",
":",
"(",
"'stateful_dirs'",
",",
")",
",",
"'has_releasedir'",
":",
"(",
"'stateful_dirs'",
",",
")",
",",
"'has_fsyncdir'",
":",
"(",
"'stateful_dirs'",
",",
")",
",",
"'has_create'",
":",
"25",
",",
"'has_access'",
":",
"25",
",",
"'has_fgetattr'",
":",
"25",
",",
"'has_ftruncate'",
":",
"25",
",",
"'has_fsinit'",
":",
"(",
"'has_init'",
")",
",",
"'has_fsdestroy'",
":",
"(",
"'has_destroy'",
")",
",",
"'has_lock'",
":",
"26",
",",
"'has_utimens'",
":",
"26",
",",
"'has_bmap'",
":",
"26",
",",
"'has_init'",
":",
"23",
",",
"'has_destroy'",
":",
"23",
",",
"'*'",
":",
"'!re:^\\*$'",
"}",
"if",
"not",
"feas",
":",
"return",
"fmap",
"def",
"resolve",
"(",
"args",
",",
"maxva",
")",
":",
"for",
"fp",
"in",
"args",
":",
"if",
"isinstance",
"(",
"fp",
",",
"int",
")",
":",
"maxva",
"[",
"0",
"]",
"=",
"max",
"(",
"maxva",
"[",
"0",
"]",
",",
"fp",
")",
"continue",
"if",
"isinstance",
"(",
"fp",
",",
"list",
")",
"or",
"isinstance",
"(",
"fp",
",",
"tuple",
")",
":",
"for",
"f",
"in",
"fp",
":",
"yield",
"f",
"continue",
"ma",
"=",
"isinstance",
"(",
"fp",
",",
"str",
")",
"and",
"re",
".",
"compile",
"(",
"\"(!\\s*|)re:(.*)\"",
")",
".",
"match",
"(",
"fp",
")",
"if",
"isinstance",
"(",
"fp",
",",
"type",
"(",
"re",
".",
"compile",
"(",
"''",
")",
")",
")",
"or",
"ma",
":",
"neg",
"=",
"False",
"if",
"ma",
":",
"mag",
"=",
"ma",
".",
"groups",
"(",
")",
"fp",
"=",
"re",
".",
"compile",
"(",
"mag",
"[",
"1",
"]",
")",
"neg",
"=",
"bool",
"(",
"mag",
"[",
"0",
"]",
")",
"for",
"f",
"in",
"list",
"(",
"fmap",
".",
"keys",
"(",
")",
")",
"+",
"[",
"'has_'",
"+",
"a",
"for",
"a",
"in",
"Fuse",
".",
"_attrs",
"]",
":",
"if",
"neg",
"!=",
"bool",
"(",
"re",
".",
"search",
"(",
"fp",
",",
"f",
")",
")",
":",
"yield",
"f",
"continue",
"ma",
"=",
"re",
".",
"compile",
"(",
"\"has_(.*)\"",
")",
".",
"match",
"(",
"fp",
")",
"if",
"ma",
"and",
"ma",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"in",
"Fuse",
".",
"_attrs",
"and",
"not",
"fp",
"in",
"fmap",
":",
"yield",
"21",
"continue",
"yield",
"fmap",
"[",
"fp",
"]",
"maxva",
"=",
"[",
"0",
"]",
"while",
"feas",
":",
"feas",
"=",
"set",
"(",
"resolve",
"(",
"feas",
",",
"maxva",
")",
")",
"return",
"maxva",
"[",
"0",
"]"
] | Get info about the FUSE API version needed for the support of some features.
This function takes a variable number of feature patterns.
A feature pattern is either:
- an integer (directly referring to a FUSE API version number)
- a built-in feature specifier string (meaning defined by dictionary)
- a string of the form ``has_foo``, where ``foo`` is a filesystem method
(refers to the API version where the method has been introduced)
- a list/tuple of other feature patterns (matches each of its members)
- a regexp (meant to be matched against the builtins plus ``has_foo``
patterns; can also be given by a string of the from "re:*")
- a negated regexp (can be given by a string of the form "!re:*")
If called with no arguments, then the list of builtins is returned, mapped
to their meaning.
Otherwise the function returns the smallest FUSE API version number which
has all the matching features.
Builtin specifiers worth to explicit mention:
- ``stateful_files``: you want to use custom filehandles (eg. a file class).
- ``*``: you want all features.
- while ``has_foo`` makes sense for all filesystem method ``foo``, some
of these can be found among the builtins, too (the ones which can be
handled by the general rule).
specifiers like ``has_foo`` refer to requirement that the library knows of
the fs method ``foo``. | [
"Get",
"info",
"about",
"the",
"FUSE",
"API",
"version",
"needed",
"for",
"the",
"support",
"of",
"some",
"features",
"."
] | 2c088b657ad71faca6975b456f80b7d2c2cea2a7 | https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuse.py#L502-L593 | train |
libfuse/python-fuse | fuse.py | FuseArgs.assemble | def assemble(self):
"""Mangle self into an argument array"""
self.canonify()
args = [sys.argv and sys.argv[0] or "python"]
if self.mountpoint:
args.append(self.mountpoint)
for m, v in self.modifiers.items():
if v:
args.append(self.fuse_modifiers[m])
opta = []
for o, v in self.optdict.items():
opta.append(o + '=' + v)
opta.extend(self.optlist)
if opta:
args.append("-o" + ",".join(opta))
return args | python | def assemble(self):
"""Mangle self into an argument array"""
self.canonify()
args = [sys.argv and sys.argv[0] or "python"]
if self.mountpoint:
args.append(self.mountpoint)
for m, v in self.modifiers.items():
if v:
args.append(self.fuse_modifiers[m])
opta = []
for o, v in self.optdict.items():
opta.append(o + '=' + v)
opta.extend(self.optlist)
if opta:
args.append("-o" + ",".join(opta))
return args | [
"def",
"assemble",
"(",
"self",
")",
":",
"self",
".",
"canonify",
"(",
")",
"args",
"=",
"[",
"sys",
".",
"argv",
"and",
"sys",
".",
"argv",
"[",
"0",
"]",
"or",
"\"python\"",
"]",
"if",
"self",
".",
"mountpoint",
":",
"args",
".",
"append",
"(",
"self",
".",
"mountpoint",
")",
"for",
"m",
",",
"v",
"in",
"self",
".",
"modifiers",
".",
"items",
"(",
")",
":",
"if",
"v",
":",
"args",
".",
"append",
"(",
"self",
".",
"fuse_modifiers",
"[",
"m",
"]",
")",
"opta",
"=",
"[",
"]",
"for",
"o",
",",
"v",
"in",
"self",
".",
"optdict",
".",
"items",
"(",
")",
":",
"opta",
".",
"append",
"(",
"o",
"+",
"'='",
"+",
"v",
")",
"opta",
".",
"extend",
"(",
"self",
".",
"optlist",
")",
"if",
"opta",
":",
"args",
".",
"append",
"(",
"\"-o\"",
"+",
"\",\"",
".",
"join",
"(",
"opta",
")",
")",
"return",
"args"
] | Mangle self into an argument array | [
"Mangle",
"self",
"into",
"an",
"argument",
"array"
] | 2c088b657ad71faca6975b456f80b7d2c2cea2a7 | https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuse.py#L129-L148 | train |
libfuse/python-fuse | fuse.py | Fuse.parse | def parse(self, *args, **kw):
"""Parse command line, fill `fuse_args` attribute."""
ev = 'errex' in kw and kw.pop('errex')
if ev and not isinstance(ev, int):
raise TypeError("error exit value should be an integer")
try:
self.cmdline = self.parser.parse_args(*args, **kw)
except OptParseError:
if ev:
sys.exit(ev)
raise
return self.fuse_args | python | def parse(self, *args, **kw):
"""Parse command line, fill `fuse_args` attribute."""
ev = 'errex' in kw and kw.pop('errex')
if ev and not isinstance(ev, int):
raise TypeError("error exit value should be an integer")
try:
self.cmdline = self.parser.parse_args(*args, **kw)
except OptParseError:
if ev:
sys.exit(ev)
raise
return self.fuse_args | [
"def",
"parse",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"ev",
"=",
"'errex'",
"in",
"kw",
"and",
"kw",
".",
"pop",
"(",
"'errex'",
")",
"if",
"ev",
"and",
"not",
"isinstance",
"(",
"ev",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"error exit value should be an integer\"",
")",
"try",
":",
"self",
".",
"cmdline",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"except",
"OptParseError",
":",
"if",
"ev",
":",
"sys",
".",
"exit",
"(",
"ev",
")",
"raise",
"return",
"self",
".",
"fuse_args"
] | Parse command line, fill `fuse_args` attribute. | [
"Parse",
"command",
"line",
"fill",
"fuse_args",
"attribute",
"."
] | 2c088b657ad71faca6975b456f80b7d2c2cea2a7 | https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuse.py#L714-L728 | train |
libfuse/python-fuse | fuse.py | Fuse.main | def main(self, args=None):
"""Enter filesystem service loop."""
if get_compat_0_1():
args = self.main_0_1_preamble()
d = {'multithreaded': self.multithreaded and 1 or 0}
d['fuse_args'] = args or self.fuse_args.assemble()
for t in 'file_class', 'dir_class':
if hasattr(self, t):
getattr(self.methproxy, 'set_' + t)(getattr(self,t))
for a in self._attrs:
b = a
if get_compat_0_1() and a in self.compatmap:
b = self.compatmap[a]
if hasattr(self, b):
c = ''
if get_compat_0_1() and hasattr(self, a + '_compat_0_1'):
c = '_compat_0_1'
d[a] = ErrnoWrapper(self.lowwrap(a + c))
try:
main(**d)
except FuseError:
if args or self.fuse_args.mount_expected():
raise | python | def main(self, args=None):
"""Enter filesystem service loop."""
if get_compat_0_1():
args = self.main_0_1_preamble()
d = {'multithreaded': self.multithreaded and 1 or 0}
d['fuse_args'] = args or self.fuse_args.assemble()
for t in 'file_class', 'dir_class':
if hasattr(self, t):
getattr(self.methproxy, 'set_' + t)(getattr(self,t))
for a in self._attrs:
b = a
if get_compat_0_1() and a in self.compatmap:
b = self.compatmap[a]
if hasattr(self, b):
c = ''
if get_compat_0_1() and hasattr(self, a + '_compat_0_1'):
c = '_compat_0_1'
d[a] = ErrnoWrapper(self.lowwrap(a + c))
try:
main(**d)
except FuseError:
if args or self.fuse_args.mount_expected():
raise | [
"def",
"main",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"if",
"get_compat_0_1",
"(",
")",
":",
"args",
"=",
"self",
".",
"main_0_1_preamble",
"(",
")",
"d",
"=",
"{",
"'multithreaded'",
":",
"self",
".",
"multithreaded",
"and",
"1",
"or",
"0",
"}",
"d",
"[",
"'fuse_args'",
"]",
"=",
"args",
"or",
"self",
".",
"fuse_args",
".",
"assemble",
"(",
")",
"for",
"t",
"in",
"'file_class'",
",",
"'dir_class'",
":",
"if",
"hasattr",
"(",
"self",
",",
"t",
")",
":",
"getattr",
"(",
"self",
".",
"methproxy",
",",
"'set_'",
"+",
"t",
")",
"(",
"getattr",
"(",
"self",
",",
"t",
")",
")",
"for",
"a",
"in",
"self",
".",
"_attrs",
":",
"b",
"=",
"a",
"if",
"get_compat_0_1",
"(",
")",
"and",
"a",
"in",
"self",
".",
"compatmap",
":",
"b",
"=",
"self",
".",
"compatmap",
"[",
"a",
"]",
"if",
"hasattr",
"(",
"self",
",",
"b",
")",
":",
"c",
"=",
"''",
"if",
"get_compat_0_1",
"(",
")",
"and",
"hasattr",
"(",
"self",
",",
"a",
"+",
"'_compat_0_1'",
")",
":",
"c",
"=",
"'_compat_0_1'",
"d",
"[",
"a",
"]",
"=",
"ErrnoWrapper",
"(",
"self",
".",
"lowwrap",
"(",
"a",
"+",
"c",
")",
")",
"try",
":",
"main",
"(",
"*",
"*",
"d",
")",
"except",
"FuseError",
":",
"if",
"args",
"or",
"self",
".",
"fuse_args",
".",
"mount_expected",
"(",
")",
":",
"raise"
] | Enter filesystem service loop. | [
"Enter",
"filesystem",
"service",
"loop",
"."
] | 2c088b657ad71faca6975b456f80b7d2c2cea2a7 | https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuse.py#L730-L757 | train |
libfuse/python-fuse | fuse.py | Fuse.fuseoptref | def fuseoptref(cls):
"""
Find out which options are recognized by the library.
Result is a `FuseArgs` instance with the list of supported
options, suitable for passing on to the `filter` method of
another `FuseArgs` instance.
"""
import os, re
pr, pw = os.pipe()
pid = os.fork()
if pid == 0:
os.dup2(pw, 2)
os.close(pr)
fh = cls()
fh.fuse_args = FuseArgs()
fh.fuse_args.setmod('showhelp')
fh.main()
sys.exit()
os.close(pw)
fa = FuseArgs()
ore = re.compile("-o\s+([\w\[\]]+(?:=\w+)?)")
fpr = os.fdopen(pr)
for l in fpr:
m = ore.search(l)
if m:
o = m.groups()[0]
oa = [o]
# try to catch two-in-one options (like "[no]foo")
opa = o.split("[")
if len(opa) == 2:
o1, ox = opa
oxpa = ox.split("]")
if len(oxpa) == 2:
oo, o2 = oxpa
oa = [o1 + o2, o1 + oo + o2]
for o in oa:
fa.add(o)
fpr.close()
return fa | python | def fuseoptref(cls):
"""
Find out which options are recognized by the library.
Result is a `FuseArgs` instance with the list of supported
options, suitable for passing on to the `filter` method of
another `FuseArgs` instance.
"""
import os, re
pr, pw = os.pipe()
pid = os.fork()
if pid == 0:
os.dup2(pw, 2)
os.close(pr)
fh = cls()
fh.fuse_args = FuseArgs()
fh.fuse_args.setmod('showhelp')
fh.main()
sys.exit()
os.close(pw)
fa = FuseArgs()
ore = re.compile("-o\s+([\w\[\]]+(?:=\w+)?)")
fpr = os.fdopen(pr)
for l in fpr:
m = ore.search(l)
if m:
o = m.groups()[0]
oa = [o]
# try to catch two-in-one options (like "[no]foo")
opa = o.split("[")
if len(opa) == 2:
o1, ox = opa
oxpa = ox.split("]")
if len(oxpa) == 2:
oo, o2 = oxpa
oa = [o1 + o2, o1 + oo + o2]
for o in oa:
fa.add(o)
fpr.close()
return fa | [
"def",
"fuseoptref",
"(",
"cls",
")",
":",
"import",
"os",
",",
"re",
"pr",
",",
"pw",
"=",
"os",
".",
"pipe",
"(",
")",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"pid",
"==",
"0",
":",
"os",
".",
"dup2",
"(",
"pw",
",",
"2",
")",
"os",
".",
"close",
"(",
"pr",
")",
"fh",
"=",
"cls",
"(",
")",
"fh",
".",
"fuse_args",
"=",
"FuseArgs",
"(",
")",
"fh",
".",
"fuse_args",
".",
"setmod",
"(",
"'showhelp'",
")",
"fh",
".",
"main",
"(",
")",
"sys",
".",
"exit",
"(",
")",
"os",
".",
"close",
"(",
"pw",
")",
"fa",
"=",
"FuseArgs",
"(",
")",
"ore",
"=",
"re",
".",
"compile",
"(",
"\"-o\\s+([\\w\\[\\]]+(?:=\\w+)?)\"",
")",
"fpr",
"=",
"os",
".",
"fdopen",
"(",
"pr",
")",
"for",
"l",
"in",
"fpr",
":",
"m",
"=",
"ore",
".",
"search",
"(",
"l",
")",
"if",
"m",
":",
"o",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"oa",
"=",
"[",
"o",
"]",
"# try to catch two-in-one options (like \"[no]foo\")",
"opa",
"=",
"o",
".",
"split",
"(",
"\"[\"",
")",
"if",
"len",
"(",
"opa",
")",
"==",
"2",
":",
"o1",
",",
"ox",
"=",
"opa",
"oxpa",
"=",
"ox",
".",
"split",
"(",
"\"]\"",
")",
"if",
"len",
"(",
"oxpa",
")",
"==",
"2",
":",
"oo",
",",
"o2",
"=",
"oxpa",
"oa",
"=",
"[",
"o1",
"+",
"o2",
",",
"o1",
"+",
"oo",
"+",
"o2",
"]",
"for",
"o",
"in",
"oa",
":",
"fa",
".",
"add",
"(",
"o",
")",
"fpr",
".",
"close",
"(",
")",
"return",
"fa"
] | Find out which options are recognized by the library.
Result is a `FuseArgs` instance with the list of supported
options, suitable for passing on to the `filter` method of
another `FuseArgs` instance. | [
"Find",
"out",
"which",
"options",
"are",
"recognized",
"by",
"the",
"library",
".",
"Result",
"is",
"a",
"FuseArgs",
"instance",
"with",
"the",
"list",
"of",
"supported",
"options",
"suitable",
"for",
"passing",
"on",
"to",
"the",
"filter",
"method",
"of",
"another",
"FuseArgs",
"instance",
"."
] | 2c088b657ad71faca6975b456f80b7d2c2cea2a7 | https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuse.py#L796-L840 | train |
libfuse/python-fuse | fuseparts/subbedopts.py | SubOptsHive.filter | def filter(self, other):
"""
Throw away those options which are not in the other one.
Returns a new instance with the rejected options.
"""
self.canonify()
other.canonify()
rej = self.__class__()
rej.optlist = self.optlist.difference(other.optlist)
self.optlist.difference_update(rej.optlist)
for x in self.optdict.copy():
if x not in other.optdict:
self.optdict.pop(x)
rej.optdict[x] = None
return rej | python | def filter(self, other):
"""
Throw away those options which are not in the other one.
Returns a new instance with the rejected options.
"""
self.canonify()
other.canonify()
rej = self.__class__()
rej.optlist = self.optlist.difference(other.optlist)
self.optlist.difference_update(rej.optlist)
for x in self.optdict.copy():
if x not in other.optdict:
self.optdict.pop(x)
rej.optdict[x] = None
return rej | [
"def",
"filter",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"canonify",
"(",
")",
"other",
".",
"canonify",
"(",
")",
"rej",
"=",
"self",
".",
"__class__",
"(",
")",
"rej",
".",
"optlist",
"=",
"self",
".",
"optlist",
".",
"difference",
"(",
"other",
".",
"optlist",
")",
"self",
".",
"optlist",
".",
"difference_update",
"(",
"rej",
".",
"optlist",
")",
"for",
"x",
"in",
"self",
".",
"optdict",
".",
"copy",
"(",
")",
":",
"if",
"x",
"not",
"in",
"other",
".",
"optdict",
":",
"self",
".",
"optdict",
".",
"pop",
"(",
"x",
")",
"rej",
".",
"optdict",
"[",
"x",
"]",
"=",
"None",
"return",
"rej"
] | Throw away those options which are not in the other one.
Returns a new instance with the rejected options. | [
"Throw",
"away",
"those",
"options",
"which",
"are",
"not",
"in",
"the",
"other",
"one",
".",
"Returns",
"a",
"new",
"instance",
"with",
"the",
"rejected",
"options",
"."
] | 2c088b657ad71faca6975b456f80b7d2c2cea2a7 | https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuseparts/subbedopts.py#L59-L76 | train |
libfuse/python-fuse | fuseparts/subbedopts.py | SubOptsHive.add | def add(self, opt, val=None):
"""Add a suboption."""
ov = opt.split('=', 1)
o = ov[0]
v = len(ov) > 1 and ov[1] or None
if (v):
if val != None:
raise AttributeError("ambiguous option value")
val = v
if val == False:
return
if val in (None, True):
self.optlist.add(o)
else:
self.optdict[o] = val | python | def add(self, opt, val=None):
"""Add a suboption."""
ov = opt.split('=', 1)
o = ov[0]
v = len(ov) > 1 and ov[1] or None
if (v):
if val != None:
raise AttributeError("ambiguous option value")
val = v
if val == False:
return
if val in (None, True):
self.optlist.add(o)
else:
self.optdict[o] = val | [
"def",
"add",
"(",
"self",
",",
"opt",
",",
"val",
"=",
"None",
")",
":",
"ov",
"=",
"opt",
".",
"split",
"(",
"'='",
",",
"1",
")",
"o",
"=",
"ov",
"[",
"0",
"]",
"v",
"=",
"len",
"(",
"ov",
")",
">",
"1",
"and",
"ov",
"[",
"1",
"]",
"or",
"None",
"if",
"(",
"v",
")",
":",
"if",
"val",
"!=",
"None",
":",
"raise",
"AttributeError",
"(",
"\"ambiguous option value\"",
")",
"val",
"=",
"v",
"if",
"val",
"==",
"False",
":",
"return",
"if",
"val",
"in",
"(",
"None",
",",
"True",
")",
":",
"self",
".",
"optlist",
".",
"add",
"(",
"o",
")",
"else",
":",
"self",
".",
"optdict",
"[",
"o",
"]",
"=",
"val"
] | Add a suboption. | [
"Add",
"a",
"suboption",
"."
] | 2c088b657ad71faca6975b456f80b7d2c2cea2a7 | https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuseparts/subbedopts.py#L78-L96 | train |
libfuse/python-fuse | fuseparts/subbedopts.py | SubbedOpt.register_sub | def register_sub(self, o):
"""Register argument a suboption for `self`."""
if o.subopt in self.subopt_map:
raise OptionConflictError(
"conflicting suboption handlers for `%s'" % o.subopt,
o)
self.subopt_map[o.subopt] = o | python | def register_sub(self, o):
"""Register argument a suboption for `self`."""
if o.subopt in self.subopt_map:
raise OptionConflictError(
"conflicting suboption handlers for `%s'" % o.subopt,
o)
self.subopt_map[o.subopt] = o | [
"def",
"register_sub",
"(",
"self",
",",
"o",
")",
":",
"if",
"o",
".",
"subopt",
"in",
"self",
".",
"subopt_map",
":",
"raise",
"OptionConflictError",
"(",
"\"conflicting suboption handlers for `%s'\"",
"%",
"o",
".",
"subopt",
",",
"o",
")",
"self",
".",
"subopt_map",
"[",
"o",
".",
"subopt",
"]",
"=",
"o"
] | Register argument a suboption for `self`. | [
"Register",
"argument",
"a",
"suboption",
"for",
"self",
"."
] | 2c088b657ad71faca6975b456f80b7d2c2cea2a7 | https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuseparts/subbedopts.py#L170-L177 | train |
tasdikrahman/vocabulary | vocabulary/vocabulary.py | Vocabulary.__parse_content | def __parse_content(tuc_content, content_to_be_parsed):
"""
parses the passed "tuc_content" for
- meanings
- synonym
received by querying the glosbe API
Called by
- meaning()
- synonym()
:param tuc_content: passed on the calling Function. A list object
:param content_to_be_parsed: data to be parsed from. Whether to parse "tuc" for meanings or synonyms
:returns: returns a list which contains the parsed data from "tuc"
"""
initial_parsed_content = {}
i = 0
for content_dict in tuc_content:
if content_to_be_parsed in content_dict.keys():
contents_raw = content_dict[content_to_be_parsed]
if content_to_be_parsed == "phrase":
# for 'phrase', 'contents_raw' is a dictionary
initial_parsed_content[i] = contents_raw['text']
i += 1
elif content_to_be_parsed == "meanings":
# for 'meanings', 'contents_raw' is a list
for meaning_content in contents_raw:
initial_parsed_content[i] = meaning_content['text']
i += 1
final_parsed_content = {}
# removing duplicates(if any) from the dictionary
for key, value in initial_parsed_content.items():
if value not in final_parsed_content.values():
final_parsed_content[key] = value
# calling __clean_dict
formatted_list = Vocabulary.__clean_dict(final_parsed_content)
return formatted_list | python | def __parse_content(tuc_content, content_to_be_parsed):
"""
parses the passed "tuc_content" for
- meanings
- synonym
received by querying the glosbe API
Called by
- meaning()
- synonym()
:param tuc_content: passed on the calling Function. A list object
:param content_to_be_parsed: data to be parsed from. Whether to parse "tuc" for meanings or synonyms
:returns: returns a list which contains the parsed data from "tuc"
"""
initial_parsed_content = {}
i = 0
for content_dict in tuc_content:
if content_to_be_parsed in content_dict.keys():
contents_raw = content_dict[content_to_be_parsed]
if content_to_be_parsed == "phrase":
# for 'phrase', 'contents_raw' is a dictionary
initial_parsed_content[i] = contents_raw['text']
i += 1
elif content_to_be_parsed == "meanings":
# for 'meanings', 'contents_raw' is a list
for meaning_content in contents_raw:
initial_parsed_content[i] = meaning_content['text']
i += 1
final_parsed_content = {}
# removing duplicates(if any) from the dictionary
for key, value in initial_parsed_content.items():
if value not in final_parsed_content.values():
final_parsed_content[key] = value
# calling __clean_dict
formatted_list = Vocabulary.__clean_dict(final_parsed_content)
return formatted_list | [
"def",
"__parse_content",
"(",
"tuc_content",
",",
"content_to_be_parsed",
")",
":",
"initial_parsed_content",
"=",
"{",
"}",
"i",
"=",
"0",
"for",
"content_dict",
"in",
"tuc_content",
":",
"if",
"content_to_be_parsed",
"in",
"content_dict",
".",
"keys",
"(",
")",
":",
"contents_raw",
"=",
"content_dict",
"[",
"content_to_be_parsed",
"]",
"if",
"content_to_be_parsed",
"==",
"\"phrase\"",
":",
"# for 'phrase', 'contents_raw' is a dictionary",
"initial_parsed_content",
"[",
"i",
"]",
"=",
"contents_raw",
"[",
"'text'",
"]",
"i",
"+=",
"1",
"elif",
"content_to_be_parsed",
"==",
"\"meanings\"",
":",
"# for 'meanings', 'contents_raw' is a list",
"for",
"meaning_content",
"in",
"contents_raw",
":",
"initial_parsed_content",
"[",
"i",
"]",
"=",
"meaning_content",
"[",
"'text'",
"]",
"i",
"+=",
"1",
"final_parsed_content",
"=",
"{",
"}",
"# removing duplicates(if any) from the dictionary",
"for",
"key",
",",
"value",
"in",
"initial_parsed_content",
".",
"items",
"(",
")",
":",
"if",
"value",
"not",
"in",
"final_parsed_content",
".",
"values",
"(",
")",
":",
"final_parsed_content",
"[",
"key",
"]",
"=",
"value",
"# calling __clean_dict",
"formatted_list",
"=",
"Vocabulary",
".",
"__clean_dict",
"(",
"final_parsed_content",
")",
"return",
"formatted_list"
] | parses the passed "tuc_content" for
- meanings
- synonym
received by querying the glosbe API
Called by
- meaning()
- synonym()
:param tuc_content: passed on the calling Function. A list object
:param content_to_be_parsed: data to be parsed from. Whether to parse "tuc" for meanings or synonyms
:returns: returns a list which contains the parsed data from "tuc" | [
"parses",
"the",
"passed",
"tuc_content",
"for",
"-",
"meanings",
"-",
"synonym",
"received",
"by",
"querying",
"the",
"glosbe",
"API"
] | 54403c5981af25dc3457796b57048ae27f09e9be | https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/vocabulary.py#L96-L136 | train |
tasdikrahman/vocabulary | vocabulary/vocabulary.py | Vocabulary.meaning | def meaning(phrase, source_lang="en", dest_lang="en", format="json"):
"""
make calls to the glosbe API
:param phrase: word for which meaning is to be found
:param source_lang: Defaults to : "en"
:param dest_lang: Defaults to : "en" For eg: "fr" for french
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid phrase
"""
base_url = Vocabulary.__get_api_link("glosbe")
url = base_url.format(word=phrase, source_lang=source_lang, dest_lang=dest_lang)
json_obj = Vocabulary.__return_json(url)
if json_obj:
try:
tuc_content = json_obj["tuc"] # "tuc_content" is a "list"
except KeyError:
return False
'''get meanings'''
meanings_list = Vocabulary.__parse_content(tuc_content, "meanings")
return Response().respond(meanings_list, format)
# print(meanings_list)
# return json.dumps(meanings_list)
else:
return False | python | def meaning(phrase, source_lang="en", dest_lang="en", format="json"):
"""
make calls to the glosbe API
:param phrase: word for which meaning is to be found
:param source_lang: Defaults to : "en"
:param dest_lang: Defaults to : "en" For eg: "fr" for french
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid phrase
"""
base_url = Vocabulary.__get_api_link("glosbe")
url = base_url.format(word=phrase, source_lang=source_lang, dest_lang=dest_lang)
json_obj = Vocabulary.__return_json(url)
if json_obj:
try:
tuc_content = json_obj["tuc"] # "tuc_content" is a "list"
except KeyError:
return False
'''get meanings'''
meanings_list = Vocabulary.__parse_content(tuc_content, "meanings")
return Response().respond(meanings_list, format)
# print(meanings_list)
# return json.dumps(meanings_list)
else:
return False | [
"def",
"meaning",
"(",
"phrase",
",",
"source_lang",
"=",
"\"en\"",
",",
"dest_lang",
"=",
"\"en\"",
",",
"format",
"=",
"\"json\"",
")",
":",
"base_url",
"=",
"Vocabulary",
".",
"__get_api_link",
"(",
"\"glosbe\"",
")",
"url",
"=",
"base_url",
".",
"format",
"(",
"word",
"=",
"phrase",
",",
"source_lang",
"=",
"source_lang",
",",
"dest_lang",
"=",
"dest_lang",
")",
"json_obj",
"=",
"Vocabulary",
".",
"__return_json",
"(",
"url",
")",
"if",
"json_obj",
":",
"try",
":",
"tuc_content",
"=",
"json_obj",
"[",
"\"tuc\"",
"]",
"# \"tuc_content\" is a \"list\"",
"except",
"KeyError",
":",
"return",
"False",
"'''get meanings'''",
"meanings_list",
"=",
"Vocabulary",
".",
"__parse_content",
"(",
"tuc_content",
",",
"\"meanings\"",
")",
"return",
"Response",
"(",
")",
".",
"respond",
"(",
"meanings_list",
",",
"format",
")",
"# print(meanings_list)",
"# return json.dumps(meanings_list)",
"else",
":",
"return",
"False"
] | make calls to the glosbe API
:param phrase: word for which meaning is to be found
:param source_lang: Defaults to : "en"
:param dest_lang: Defaults to : "en" For eg: "fr" for french
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid phrase | [
"make",
"calls",
"to",
"the",
"glosbe",
"API"
] | 54403c5981af25dc3457796b57048ae27f09e9be | https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/vocabulary.py#L161-L186 | train |
tasdikrahman/vocabulary | vocabulary/vocabulary.py | Vocabulary.part_of_speech | def part_of_speech(phrase, format='json'):
"""
querrying Wordnik's API for knowing whether the word is a noun, adjective and the like
:params phrase: word for which part_of_speech is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid phrase
"""
# We get a list object as a return value from the Wordnik API
base_url = Vocabulary.__get_api_link("wordnik")
url = base_url.format(word=phrase.lower(), action="definitions")
json_obj = Vocabulary.__return_json(url)
if not json_obj:
return False
result = []
for idx, obj in enumerate(json_obj):
text = obj.get('partOfSpeech', None)
example = obj.get('text', None)
result.append({"seq": idx, "text": text, "example": example})
return Response().respond(result, format) | python | def part_of_speech(phrase, format='json'):
"""
querrying Wordnik's API for knowing whether the word is a noun, adjective and the like
:params phrase: word for which part_of_speech is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid phrase
"""
# We get a list object as a return value from the Wordnik API
base_url = Vocabulary.__get_api_link("wordnik")
url = base_url.format(word=phrase.lower(), action="definitions")
json_obj = Vocabulary.__return_json(url)
if not json_obj:
return False
result = []
for idx, obj in enumerate(json_obj):
text = obj.get('partOfSpeech', None)
example = obj.get('text', None)
result.append({"seq": idx, "text": text, "example": example})
return Response().respond(result, format) | [
"def",
"part_of_speech",
"(",
"phrase",
",",
"format",
"=",
"'json'",
")",
":",
"# We get a list object as a return value from the Wordnik API",
"base_url",
"=",
"Vocabulary",
".",
"__get_api_link",
"(",
"\"wordnik\"",
")",
"url",
"=",
"base_url",
".",
"format",
"(",
"word",
"=",
"phrase",
".",
"lower",
"(",
")",
",",
"action",
"=",
"\"definitions\"",
")",
"json_obj",
"=",
"Vocabulary",
".",
"__return_json",
"(",
"url",
")",
"if",
"not",
"json_obj",
":",
"return",
"False",
"result",
"=",
"[",
"]",
"for",
"idx",
",",
"obj",
"in",
"enumerate",
"(",
"json_obj",
")",
":",
"text",
"=",
"obj",
".",
"get",
"(",
"'partOfSpeech'",
",",
"None",
")",
"example",
"=",
"obj",
".",
"get",
"(",
"'text'",
",",
"None",
")",
"result",
".",
"append",
"(",
"{",
"\"seq\"",
":",
"idx",
",",
"\"text\"",
":",
"text",
",",
"\"example\"",
":",
"example",
"}",
")",
"return",
"Response",
"(",
")",
".",
"respond",
"(",
"result",
",",
"format",
")"
] | querrying Wordnik's API for knowing whether the word is a noun, adjective and the like
:params phrase: word for which part_of_speech is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid phrase | [
"querrying",
"Wordnik",
"s",
"API",
"for",
"knowing",
"whether",
"the",
"word",
"is",
"a",
"noun",
"adjective",
"and",
"the",
"like"
] | 54403c5981af25dc3457796b57048ae27f09e9be | https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/vocabulary.py#L304-L326 | train |
tasdikrahman/vocabulary | vocabulary/vocabulary.py | Vocabulary.usage_example | def usage_example(phrase, format='json'):
"""Takes the source phrase and queries it to the urbandictionary API
:params phrase: word for which usage_example is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid phrase
"""
base_url = Vocabulary.__get_api_link("urbandict")
url = base_url.format(action="define", word=phrase)
word_examples = {}
json_obj = Vocabulary.__return_json(url)
if json_obj:
examples_list = json_obj["list"]
for i, example in enumerate(examples_list):
if example["thumbs_up"] > example["thumbs_down"]:
word_examples[i] = example["example"].replace("\r", "").replace("\n", "")
if word_examples:
# reforamatting "word_examples" using "__clean_dict()"
# return json.dumps(Vocabulary.__clean_dict(word_examples))
# return Vocabulary.__clean_dict(word_examples)
return Response().respond(Vocabulary.__clean_dict(word_examples), format)
else:
return False
else:
return False | python | def usage_example(phrase, format='json'):
"""Takes the source phrase and queries it to the urbandictionary API
:params phrase: word for which usage_example is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid phrase
"""
base_url = Vocabulary.__get_api_link("urbandict")
url = base_url.format(action="define", word=phrase)
word_examples = {}
json_obj = Vocabulary.__return_json(url)
if json_obj:
examples_list = json_obj["list"]
for i, example in enumerate(examples_list):
if example["thumbs_up"] > example["thumbs_down"]:
word_examples[i] = example["example"].replace("\r", "").replace("\n", "")
if word_examples:
# reforamatting "word_examples" using "__clean_dict()"
# return json.dumps(Vocabulary.__clean_dict(word_examples))
# return Vocabulary.__clean_dict(word_examples)
return Response().respond(Vocabulary.__clean_dict(word_examples), format)
else:
return False
else:
return False | [
"def",
"usage_example",
"(",
"phrase",
",",
"format",
"=",
"'json'",
")",
":",
"base_url",
"=",
"Vocabulary",
".",
"__get_api_link",
"(",
"\"urbandict\"",
")",
"url",
"=",
"base_url",
".",
"format",
"(",
"action",
"=",
"\"define\"",
",",
"word",
"=",
"phrase",
")",
"word_examples",
"=",
"{",
"}",
"json_obj",
"=",
"Vocabulary",
".",
"__return_json",
"(",
"url",
")",
"if",
"json_obj",
":",
"examples_list",
"=",
"json_obj",
"[",
"\"list\"",
"]",
"for",
"i",
",",
"example",
"in",
"enumerate",
"(",
"examples_list",
")",
":",
"if",
"example",
"[",
"\"thumbs_up\"",
"]",
">",
"example",
"[",
"\"thumbs_down\"",
"]",
":",
"word_examples",
"[",
"i",
"]",
"=",
"example",
"[",
"\"example\"",
"]",
".",
"replace",
"(",
"\"\\r\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",
"if",
"word_examples",
":",
"# reforamatting \"word_examples\" using \"__clean_dict()\"",
"# return json.dumps(Vocabulary.__clean_dict(word_examples))",
"# return Vocabulary.__clean_dict(word_examples)",
"return",
"Response",
"(",
")",
".",
"respond",
"(",
"Vocabulary",
".",
"__clean_dict",
"(",
"word_examples",
")",
",",
"format",
")",
"else",
":",
"return",
"False",
"else",
":",
"return",
"False"
] | Takes the source phrase and queries it to the urbandictionary API
:params phrase: word for which usage_example is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid phrase | [
"Takes",
"the",
"source",
"phrase",
"and",
"queries",
"it",
"to",
"the",
"urbandictionary",
"API"
] | 54403c5981af25dc3457796b57048ae27f09e9be | https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/vocabulary.py#L329-L353 | train |
tasdikrahman/vocabulary | vocabulary/vocabulary.py | Vocabulary.pronunciation | def pronunciation(phrase, format='json'):
"""
Gets the pronunciation from the Wordnik API
:params phrase: word for which pronunciation is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a list object, False if invalid phrase
"""
base_url = Vocabulary.__get_api_link("wordnik")
url = base_url.format(word=phrase.lower(), action="pronunciations")
json_obj = Vocabulary.__return_json(url)
if json_obj:
'''
Refer : http://stackoverflow.com/q/18337407/3834059
'''
## TODO: Fix the unicode issue mentioned in
## https://github.com/tasdikrahman/vocabulary#181known-issues
for idx, obj in enumerate(json_obj):
obj['seq'] = idx
if sys.version_info[:2] <= (2, 7): ## python2
# return json_obj
return Response().respond(json_obj, format)
else: # python3
# return json.loads(json.dumps(json_obj, ensure_ascii=False))
return Response().respond(json_obj, format)
else:
return False | python | def pronunciation(phrase, format='json'):
"""
Gets the pronunciation from the Wordnik API
:params phrase: word for which pronunciation is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a list object, False if invalid phrase
"""
base_url = Vocabulary.__get_api_link("wordnik")
url = base_url.format(word=phrase.lower(), action="pronunciations")
json_obj = Vocabulary.__return_json(url)
if json_obj:
'''
Refer : http://stackoverflow.com/q/18337407/3834059
'''
## TODO: Fix the unicode issue mentioned in
## https://github.com/tasdikrahman/vocabulary#181known-issues
for idx, obj in enumerate(json_obj):
obj['seq'] = idx
if sys.version_info[:2] <= (2, 7): ## python2
# return json_obj
return Response().respond(json_obj, format)
else: # python3
# return json.loads(json.dumps(json_obj, ensure_ascii=False))
return Response().respond(json_obj, format)
else:
return False | [
"def",
"pronunciation",
"(",
"phrase",
",",
"format",
"=",
"'json'",
")",
":",
"base_url",
"=",
"Vocabulary",
".",
"__get_api_link",
"(",
"\"wordnik\"",
")",
"url",
"=",
"base_url",
".",
"format",
"(",
"word",
"=",
"phrase",
".",
"lower",
"(",
")",
",",
"action",
"=",
"\"pronunciations\"",
")",
"json_obj",
"=",
"Vocabulary",
".",
"__return_json",
"(",
"url",
")",
"if",
"json_obj",
":",
"'''\n Refer : http://stackoverflow.com/q/18337407/3834059\n '''",
"## TODO: Fix the unicode issue mentioned in",
"## https://github.com/tasdikrahman/vocabulary#181known-issues",
"for",
"idx",
",",
"obj",
"in",
"enumerate",
"(",
"json_obj",
")",
":",
"obj",
"[",
"'seq'",
"]",
"=",
"idx",
"if",
"sys",
".",
"version_info",
"[",
":",
"2",
"]",
"<=",
"(",
"2",
",",
"7",
")",
":",
"## python2",
"# return json_obj",
"return",
"Response",
"(",
")",
".",
"respond",
"(",
"json_obj",
",",
"format",
")",
"else",
":",
"# python3",
"# return json.loads(json.dumps(json_obj, ensure_ascii=False))",
"return",
"Response",
"(",
")",
".",
"respond",
"(",
"json_obj",
",",
"format",
")",
"else",
":",
"return",
"False"
] | Gets the pronunciation from the Wordnik API
:params phrase: word for which pronunciation is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a list object, False if invalid phrase | [
"Gets",
"the",
"pronunciation",
"from",
"the",
"Wordnik",
"API"
] | 54403c5981af25dc3457796b57048ae27f09e9be | https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/vocabulary.py#L356-L383 | train |
tasdikrahman/vocabulary | vocabulary/vocabulary.py | Vocabulary.hyphenation | def hyphenation(phrase, format='json'):
"""
Returns back the stress points in the "phrase" passed
:param phrase: word for which hyphenation is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid phrase
"""
base_url = Vocabulary.__get_api_link("wordnik")
url = base_url.format(word=phrase.lower(), action="hyphenation")
json_obj = Vocabulary.__return_json(url)
if json_obj:
# return json.dumps(json_obj)
# return json_obj
return Response().respond(json_obj, format)
else:
return False | python | def hyphenation(phrase, format='json'):
"""
Returns back the stress points in the "phrase" passed
:param phrase: word for which hyphenation is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid phrase
"""
base_url = Vocabulary.__get_api_link("wordnik")
url = base_url.format(word=phrase.lower(), action="hyphenation")
json_obj = Vocabulary.__return_json(url)
if json_obj:
# return json.dumps(json_obj)
# return json_obj
return Response().respond(json_obj, format)
else:
return False | [
"def",
"hyphenation",
"(",
"phrase",
",",
"format",
"=",
"'json'",
")",
":",
"base_url",
"=",
"Vocabulary",
".",
"__get_api_link",
"(",
"\"wordnik\"",
")",
"url",
"=",
"base_url",
".",
"format",
"(",
"word",
"=",
"phrase",
".",
"lower",
"(",
")",
",",
"action",
"=",
"\"hyphenation\"",
")",
"json_obj",
"=",
"Vocabulary",
".",
"__return_json",
"(",
"url",
")",
"if",
"json_obj",
":",
"# return json.dumps(json_obj)",
"# return json_obj",
"return",
"Response",
"(",
")",
".",
"respond",
"(",
"json_obj",
",",
"format",
")",
"else",
":",
"return",
"False"
] | Returns back the stress points in the "phrase" passed
:param phrase: word for which hyphenation is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid phrase | [
"Returns",
"back",
"the",
"stress",
"points",
"in",
"the",
"phrase",
"passed"
] | 54403c5981af25dc3457796b57048ae27f09e9be | https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/vocabulary.py#L386-L402 | train |
tasdikrahman/vocabulary | vocabulary/responselib.py | Response.__respond_with_dict | def __respond_with_dict(self, data):
"""
Builds a python dictionary from a json object
:param data: the json object
:returns: a nested dictionary
"""
response = {}
if isinstance(data, list):
temp_data, data = data, {}
for key, value in enumerate(temp_data):
data[key] = value
data.pop('seq', None)
for index, item in data.items():
values = item
if isinstance(item, list) or isinstance(item, dict):
values = self.__respond_with_dict(item)
if isinstance(values, dict) and len(values) == 1:
(key, values), = values.items()
response[index] = values
return response | python | def __respond_with_dict(self, data):
"""
Builds a python dictionary from a json object
:param data: the json object
:returns: a nested dictionary
"""
response = {}
if isinstance(data, list):
temp_data, data = data, {}
for key, value in enumerate(temp_data):
data[key] = value
data.pop('seq', None)
for index, item in data.items():
values = item
if isinstance(item, list) or isinstance(item, dict):
values = self.__respond_with_dict(item)
if isinstance(values, dict) and len(values) == 1:
(key, values), = values.items()
response[index] = values
return response | [
"def",
"__respond_with_dict",
"(",
"self",
",",
"data",
")",
":",
"response",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"temp_data",
",",
"data",
"=",
"data",
",",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"enumerate",
"(",
"temp_data",
")",
":",
"data",
"[",
"key",
"]",
"=",
"value",
"data",
".",
"pop",
"(",
"'seq'",
",",
"None",
")",
"for",
"index",
",",
"item",
"in",
"data",
".",
"items",
"(",
")",
":",
"values",
"=",
"item",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
"or",
"isinstance",
"(",
"item",
",",
"dict",
")",
":",
"values",
"=",
"self",
".",
"__respond_with_dict",
"(",
"item",
")",
"if",
"isinstance",
"(",
"values",
",",
"dict",
")",
"and",
"len",
"(",
"values",
")",
"==",
"1",
":",
"(",
"key",
",",
"values",
")",
",",
"=",
"values",
".",
"items",
"(",
")",
"response",
"[",
"index",
"]",
"=",
"values",
"return",
"response"
] | Builds a python dictionary from a json object
:param data: the json object
:returns: a nested dictionary | [
"Builds",
"a",
"python",
"dictionary",
"from",
"a",
"json",
"object"
] | 54403c5981af25dc3457796b57048ae27f09e9be | https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/responselib.py#L39-L62 | train |
tasdikrahman/vocabulary | vocabulary/responselib.py | Response.__respond_with_list | def __respond_with_list(self, data):
"""
Builds a python list from a json object
:param data: the json object
:returns: a nested list
"""
response = []
if isinstance(data, dict):
data.pop('seq', None)
data = list(data.values())
for item in data:
values = item
if isinstance(item, list) or isinstance(item, dict):
values = self.__respond_with_list(item)
if isinstance(values, list) and len(values) == 1:
response.extend(values)
else:
response.append(values)
return response | python | def __respond_with_list(self, data):
"""
Builds a python list from a json object
:param data: the json object
:returns: a nested list
"""
response = []
if isinstance(data, dict):
data.pop('seq', None)
data = list(data.values())
for item in data:
values = item
if isinstance(item, list) or isinstance(item, dict):
values = self.__respond_with_list(item)
if isinstance(values, list) and len(values) == 1:
response.extend(values)
else:
response.append(values)
return response | [
"def",
"__respond_with_list",
"(",
"self",
",",
"data",
")",
":",
"response",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"data",
".",
"pop",
"(",
"'seq'",
",",
"None",
")",
"data",
"=",
"list",
"(",
"data",
".",
"values",
"(",
")",
")",
"for",
"item",
"in",
"data",
":",
"values",
"=",
"item",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
"or",
"isinstance",
"(",
"item",
",",
"dict",
")",
":",
"values",
"=",
"self",
".",
"__respond_with_list",
"(",
"item",
")",
"if",
"isinstance",
"(",
"values",
",",
"list",
")",
"and",
"len",
"(",
"values",
")",
"==",
"1",
":",
"response",
".",
"extend",
"(",
"values",
")",
"else",
":",
"response",
".",
"append",
"(",
"values",
")",
"return",
"response"
] | Builds a python list from a json object
:param data: the json object
:returns: a nested list | [
"Builds",
"a",
"python",
"list",
"from",
"a",
"json",
"object"
] | 54403c5981af25dc3457796b57048ae27f09e9be | https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/responselib.py#L64-L86 | train |
tasdikrahman/vocabulary | vocabulary/responselib.py | Response.respond | def respond(self, data, format='json'):
"""
Converts a json object to a python datastructure based on
specified format
:param data: the json object
:param format: python datastructure type. Defaults to: "json"
:returns: a python specified object
"""
dispatchers = {
"dict": self.__respond_with_dict,
"list": self.__respond_with_list
}
if not dispatchers.get(format, False):
return json.dumps(data)
return dispatchers[format](data) | python | def respond(self, data, format='json'):
"""
Converts a json object to a python datastructure based on
specified format
:param data: the json object
:param format: python datastructure type. Defaults to: "json"
:returns: a python specified object
"""
dispatchers = {
"dict": self.__respond_with_dict,
"list": self.__respond_with_list
}
if not dispatchers.get(format, False):
return json.dumps(data)
return dispatchers[format](data) | [
"def",
"respond",
"(",
"self",
",",
"data",
",",
"format",
"=",
"'json'",
")",
":",
"dispatchers",
"=",
"{",
"\"dict\"",
":",
"self",
".",
"__respond_with_dict",
",",
"\"list\"",
":",
"self",
".",
"__respond_with_list",
"}",
"if",
"not",
"dispatchers",
".",
"get",
"(",
"format",
",",
"False",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"data",
")",
"return",
"dispatchers",
"[",
"format",
"]",
"(",
"data",
")"
] | Converts a json object to a python datastructure based on
specified format
:param data: the json object
:param format: python datastructure type. Defaults to: "json"
:returns: a python specified object | [
"Converts",
"a",
"json",
"object",
"to",
"a",
"python",
"datastructure",
"based",
"on",
"specified",
"format"
] | 54403c5981af25dc3457796b57048ae27f09e9be | https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/responselib.py#L88-L105 | train |
bram85/topydo | topydo/lib/MultiCommand.py | MultiCommand.get_todos | def get_todos(self):
""" Gets todo objects from supplied todo IDs. """
if self.is_expression:
self.get_todos_from_expr()
else:
if self.last_argument:
numbers = self.args[:-1]
else:
numbers = self.args
for number in numbers:
try:
self.todos.append(self.todolist.todo(number))
except InvalidTodoException:
self.invalid_numbers.append(number) | python | def get_todos(self):
""" Gets todo objects from supplied todo IDs. """
if self.is_expression:
self.get_todos_from_expr()
else:
if self.last_argument:
numbers = self.args[:-1]
else:
numbers = self.args
for number in numbers:
try:
self.todos.append(self.todolist.todo(number))
except InvalidTodoException:
self.invalid_numbers.append(number) | [
"def",
"get_todos",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_expression",
":",
"self",
".",
"get_todos_from_expr",
"(",
")",
"else",
":",
"if",
"self",
".",
"last_argument",
":",
"numbers",
"=",
"self",
".",
"args",
"[",
":",
"-",
"1",
"]",
"else",
":",
"numbers",
"=",
"self",
".",
"args",
"for",
"number",
"in",
"numbers",
":",
"try",
":",
"self",
".",
"todos",
".",
"append",
"(",
"self",
".",
"todolist",
".",
"todo",
"(",
"number",
")",
")",
"except",
"InvalidTodoException",
":",
"self",
".",
"invalid_numbers",
".",
"append",
"(",
"number",
")"
] | Gets todo objects from supplied todo IDs. | [
"Gets",
"todo",
"objects",
"from",
"supplied",
"todo",
"IDs",
"."
] | b59fcfca5361869a6b78d4c9808c7c6cd0a18b58 | https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/MultiCommand.py#L64-L78 | train |
bram85/topydo | topydo/ui/columns/TodoWidget.py | _markup | def _markup(p_todo, p_focus):
"""
Returns an attribute spec for the colors that correspond to the given todo
item.
"""
pri = p_todo.priority()
pri = 'pri_' + pri if pri else PaletteItem.DEFAULT
if not p_focus:
attr_dict = {None: pri}
else:
# use '_focus' palette entries instead of standard ones
attr_dict = {None: pri + '_focus'}
attr_dict[PaletteItem.PROJECT] = PaletteItem.PROJECT_FOCUS
attr_dict[PaletteItem.CONTEXT] = PaletteItem.CONTEXT_FOCUS
attr_dict[PaletteItem.METADATA] = PaletteItem.METADATA_FOCUS
attr_dict[PaletteItem.LINK] = PaletteItem.LINK_FOCUS
return attr_dict | python | def _markup(p_todo, p_focus):
"""
Returns an attribute spec for the colors that correspond to the given todo
item.
"""
pri = p_todo.priority()
pri = 'pri_' + pri if pri else PaletteItem.DEFAULT
if not p_focus:
attr_dict = {None: pri}
else:
# use '_focus' palette entries instead of standard ones
attr_dict = {None: pri + '_focus'}
attr_dict[PaletteItem.PROJECT] = PaletteItem.PROJECT_FOCUS
attr_dict[PaletteItem.CONTEXT] = PaletteItem.CONTEXT_FOCUS
attr_dict[PaletteItem.METADATA] = PaletteItem.METADATA_FOCUS
attr_dict[PaletteItem.LINK] = PaletteItem.LINK_FOCUS
return attr_dict | [
"def",
"_markup",
"(",
"p_todo",
",",
"p_focus",
")",
":",
"pri",
"=",
"p_todo",
".",
"priority",
"(",
")",
"pri",
"=",
"'pri_'",
"+",
"pri",
"if",
"pri",
"else",
"PaletteItem",
".",
"DEFAULT",
"if",
"not",
"p_focus",
":",
"attr_dict",
"=",
"{",
"None",
":",
"pri",
"}",
"else",
":",
"# use '_focus' palette entries instead of standard ones",
"attr_dict",
"=",
"{",
"None",
":",
"pri",
"+",
"'_focus'",
"}",
"attr_dict",
"[",
"PaletteItem",
".",
"PROJECT",
"]",
"=",
"PaletteItem",
".",
"PROJECT_FOCUS",
"attr_dict",
"[",
"PaletteItem",
".",
"CONTEXT",
"]",
"=",
"PaletteItem",
".",
"CONTEXT_FOCUS",
"attr_dict",
"[",
"PaletteItem",
".",
"METADATA",
"]",
"=",
"PaletteItem",
".",
"METADATA_FOCUS",
"attr_dict",
"[",
"PaletteItem",
".",
"LINK",
"]",
"=",
"PaletteItem",
".",
"LINK_FOCUS",
"return",
"attr_dict"
] | Returns an attribute spec for the colors that correspond to the given todo
item. | [
"Returns",
"an",
"attribute",
"spec",
"for",
"the",
"colors",
"that",
"correspond",
"to",
"the",
"given",
"todo",
"item",
"."
] | b59fcfca5361869a6b78d4c9808c7c6cd0a18b58 | https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/TodoWidget.py#L35-L53 | train |
bram85/topydo | topydo/ui/columns/TodoWidget.py | TodoWidget.create | def create(p_class, p_todo, p_id_width=4):
"""
Creates a TodoWidget instance for the given todo. Widgets are
cached, the same object is returned for the same todo item.
"""
def parent_progress_may_have_changed(p_todo):
"""
Returns True when a todo's progress should be updated because it is
dependent on the parent's progress.
"""
return p_todo.has_tag('p') and not p_todo.has_tag('due')
source = p_todo.source()
if source in p_class.cache:
widget = p_class.cache[source]
if p_todo is not widget.todo:
# same source text but different todo instance (could happen
# after an edit where a new Todo instance is created with the
# same text as before)
# simply fix the reference in the stored widget.
widget.todo = p_todo
if parent_progress_may_have_changed(p_todo):
widget.update_progress()
else:
widget = p_class(p_todo, p_id_width)
p_class.cache[source] = widget
return widget | python | def create(p_class, p_todo, p_id_width=4):
"""
Creates a TodoWidget instance for the given todo. Widgets are
cached, the same object is returned for the same todo item.
"""
def parent_progress_may_have_changed(p_todo):
"""
Returns True when a todo's progress should be updated because it is
dependent on the parent's progress.
"""
return p_todo.has_tag('p') and not p_todo.has_tag('due')
source = p_todo.source()
if source in p_class.cache:
widget = p_class.cache[source]
if p_todo is not widget.todo:
# same source text but different todo instance (could happen
# after an edit where a new Todo instance is created with the
# same text as before)
# simply fix the reference in the stored widget.
widget.todo = p_todo
if parent_progress_may_have_changed(p_todo):
widget.update_progress()
else:
widget = p_class(p_todo, p_id_width)
p_class.cache[source] = widget
return widget | [
"def",
"create",
"(",
"p_class",
",",
"p_todo",
",",
"p_id_width",
"=",
"4",
")",
":",
"def",
"parent_progress_may_have_changed",
"(",
"p_todo",
")",
":",
"\"\"\"\n Returns True when a todo's progress should be updated because it is\n dependent on the parent's progress.\n \"\"\"",
"return",
"p_todo",
".",
"has_tag",
"(",
"'p'",
")",
"and",
"not",
"p_todo",
".",
"has_tag",
"(",
"'due'",
")",
"source",
"=",
"p_todo",
".",
"source",
"(",
")",
"if",
"source",
"in",
"p_class",
".",
"cache",
":",
"widget",
"=",
"p_class",
".",
"cache",
"[",
"source",
"]",
"if",
"p_todo",
"is",
"not",
"widget",
".",
"todo",
":",
"# same source text but different todo instance (could happen",
"# after an edit where a new Todo instance is created with the",
"# same text as before)",
"# simply fix the reference in the stored widget.",
"widget",
".",
"todo",
"=",
"p_todo",
"if",
"parent_progress_may_have_changed",
"(",
"p_todo",
")",
":",
"widget",
".",
"update_progress",
"(",
")",
"else",
":",
"widget",
"=",
"p_class",
"(",
"p_todo",
",",
"p_id_width",
")",
"p_class",
".",
"cache",
"[",
"source",
"]",
"=",
"widget",
"return",
"widget"
] | Creates a TodoWidget instance for the given todo. Widgets are
cached, the same object is returned for the same todo item. | [
"Creates",
"a",
"TodoWidget",
"instance",
"for",
"the",
"given",
"todo",
".",
"Widgets",
"are",
"cached",
"the",
"same",
"object",
"is",
"returned",
"for",
"the",
"same",
"todo",
"item",
"."
] | b59fcfca5361869a6b78d4c9808c7c6cd0a18b58 | https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/TodoWidget.py#L164-L195 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.