id
int32 0
252k
| 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
11,300
|
coldfix/udiskie
|
udiskie/mount.py
|
Mounter.get_device_tree
|
def get_device_tree(self):
"""Get a tree of all devices."""
root = DevNode(None, None, [], None)
device_nodes = {
dev.object_path: DevNode(dev, dev.parent_object_path, [],
self._ignore_device(dev))
for dev in self.udisks
}
for node in device_nodes.values():
device_nodes.get(node.root, root).children.append(node)
device_nodes['/'] = root
for node in device_nodes.values():
node.children.sort(key=DevNode._sort_key)
# use parent as fallback, update top->down:
def propagate_ignored(node):
for child in node.children:
if child.ignored is None:
child.ignored = node.ignored
propagate_ignored(child)
propagate_ignored(root)
return device_nodes
|
python
|
def get_device_tree(self):
"""Get a tree of all devices."""
root = DevNode(None, None, [], None)
device_nodes = {
dev.object_path: DevNode(dev, dev.parent_object_path, [],
self._ignore_device(dev))
for dev in self.udisks
}
for node in device_nodes.values():
device_nodes.get(node.root, root).children.append(node)
device_nodes['/'] = root
for node in device_nodes.values():
node.children.sort(key=DevNode._sort_key)
# use parent as fallback, update top->down:
def propagate_ignored(node):
for child in node.children:
if child.ignored is None:
child.ignored = node.ignored
propagate_ignored(child)
propagate_ignored(root)
return device_nodes
|
[
"def",
"get_device_tree",
"(",
"self",
")",
":",
"root",
"=",
"DevNode",
"(",
"None",
",",
"None",
",",
"[",
"]",
",",
"None",
")",
"device_nodes",
"=",
"{",
"dev",
".",
"object_path",
":",
"DevNode",
"(",
"dev",
",",
"dev",
".",
"parent_object_path",
",",
"[",
"]",
",",
"self",
".",
"_ignore_device",
"(",
"dev",
")",
")",
"for",
"dev",
"in",
"self",
".",
"udisks",
"}",
"for",
"node",
"in",
"device_nodes",
".",
"values",
"(",
")",
":",
"device_nodes",
".",
"get",
"(",
"node",
".",
"root",
",",
"root",
")",
".",
"children",
".",
"append",
"(",
"node",
")",
"device_nodes",
"[",
"'/'",
"]",
"=",
"root",
"for",
"node",
"in",
"device_nodes",
".",
"values",
"(",
")",
":",
"node",
".",
"children",
".",
"sort",
"(",
"key",
"=",
"DevNode",
".",
"_sort_key",
")",
"# use parent as fallback, update top->down:",
"def",
"propagate_ignored",
"(",
"node",
")",
":",
"for",
"child",
"in",
"node",
".",
"children",
":",
"if",
"child",
".",
"ignored",
"is",
"None",
":",
"child",
".",
"ignored",
"=",
"node",
".",
"ignored",
"propagate_ignored",
"(",
"child",
")",
"propagate_ignored",
"(",
"root",
")",
"return",
"device_nodes"
] |
Get a tree of all devices.
|
[
"Get",
"a",
"tree",
"of",
"all",
"devices",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L713-L734
|
11,301
|
coldfix/udiskie
|
udiskie/mount.py
|
DeviceActions.detect
|
def detect(self, root_device='/'):
"""
Detect all currently known devices.
:param str root_device: object path of root device to return
:returns: root node of device hierarchy
"""
root = Device(None, [], None, "", [])
device_nodes = dict(map(self._device_node,
self._mounter.get_all_handleable()))
# insert child devices as branches into their roots:
for node in device_nodes.values():
device_nodes.get(node.root, root).branches.append(node)
device_nodes['/'] = root
for node in device_nodes.values():
node.branches.sort(key=lambda node: node.label)
return device_nodes[root_device]
|
python
|
def detect(self, root_device='/'):
"""
Detect all currently known devices.
:param str root_device: object path of root device to return
:returns: root node of device hierarchy
"""
root = Device(None, [], None, "", [])
device_nodes = dict(map(self._device_node,
self._mounter.get_all_handleable()))
# insert child devices as branches into their roots:
for node in device_nodes.values():
device_nodes.get(node.root, root).branches.append(node)
device_nodes['/'] = root
for node in device_nodes.values():
node.branches.sort(key=lambda node: node.label)
return device_nodes[root_device]
|
[
"def",
"detect",
"(",
"self",
",",
"root_device",
"=",
"'/'",
")",
":",
"root",
"=",
"Device",
"(",
"None",
",",
"[",
"]",
",",
"None",
",",
"\"\"",
",",
"[",
"]",
")",
"device_nodes",
"=",
"dict",
"(",
"map",
"(",
"self",
".",
"_device_node",
",",
"self",
".",
"_mounter",
".",
"get_all_handleable",
"(",
")",
")",
")",
"# insert child devices as branches into their roots:",
"for",
"node",
"in",
"device_nodes",
".",
"values",
"(",
")",
":",
"device_nodes",
".",
"get",
"(",
"node",
".",
"root",
",",
"root",
")",
".",
"branches",
".",
"append",
"(",
"node",
")",
"device_nodes",
"[",
"'/'",
"]",
"=",
"root",
"for",
"node",
"in",
"device_nodes",
".",
"values",
"(",
")",
":",
"node",
".",
"branches",
".",
"sort",
"(",
"key",
"=",
"lambda",
"node",
":",
"node",
".",
"label",
")",
"return",
"device_nodes",
"[",
"root_device",
"]"
] |
Detect all currently known devices.
:param str root_device: object path of root device to return
:returns: root node of device hierarchy
|
[
"Detect",
"all",
"currently",
"known",
"devices",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L785-L801
|
11,302
|
coldfix/udiskie
|
udiskie/mount.py
|
DeviceActions._get_device_methods
|
def _get_device_methods(self, device):
"""Return an iterable over all available methods the device has."""
if device.is_filesystem:
if device.is_mounted:
if self._mounter._browser:
yield 'browse'
if self._mounter._terminal:
yield 'terminal'
yield 'unmount'
else:
yield 'mount'
elif device.is_crypto:
if device.is_unlocked:
yield 'lock'
else:
yield 'unlock'
cache = self._mounter._cache
if cache and device in cache:
yield 'forget_password'
if device.is_ejectable and device.has_media:
yield 'eject'
if device.is_detachable:
yield 'detach'
if device.is_loop:
yield 'delete'
|
python
|
def _get_device_methods(self, device):
"""Return an iterable over all available methods the device has."""
if device.is_filesystem:
if device.is_mounted:
if self._mounter._browser:
yield 'browse'
if self._mounter._terminal:
yield 'terminal'
yield 'unmount'
else:
yield 'mount'
elif device.is_crypto:
if device.is_unlocked:
yield 'lock'
else:
yield 'unlock'
cache = self._mounter._cache
if cache and device in cache:
yield 'forget_password'
if device.is_ejectable and device.has_media:
yield 'eject'
if device.is_detachable:
yield 'detach'
if device.is_loop:
yield 'delete'
|
[
"def",
"_get_device_methods",
"(",
"self",
",",
"device",
")",
":",
"if",
"device",
".",
"is_filesystem",
":",
"if",
"device",
".",
"is_mounted",
":",
"if",
"self",
".",
"_mounter",
".",
"_browser",
":",
"yield",
"'browse'",
"if",
"self",
".",
"_mounter",
".",
"_terminal",
":",
"yield",
"'terminal'",
"yield",
"'unmount'",
"else",
":",
"yield",
"'mount'",
"elif",
"device",
".",
"is_crypto",
":",
"if",
"device",
".",
"is_unlocked",
":",
"yield",
"'lock'",
"else",
":",
"yield",
"'unlock'",
"cache",
"=",
"self",
".",
"_mounter",
".",
"_cache",
"if",
"cache",
"and",
"device",
"in",
"cache",
":",
"yield",
"'forget_password'",
"if",
"device",
".",
"is_ejectable",
"and",
"device",
".",
"has_media",
":",
"yield",
"'eject'",
"if",
"device",
".",
"is_detachable",
":",
"yield",
"'detach'",
"if",
"device",
".",
"is_loop",
":",
"yield",
"'delete'"
] |
Return an iterable over all available methods the device has.
|
[
"Return",
"an",
"iterable",
"over",
"all",
"available",
"methods",
"the",
"device",
"has",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L803-L827
|
11,303
|
coldfix/udiskie
|
udiskie/mount.py
|
DeviceActions._device_node
|
def _device_node(self, device):
"""Create an empty menu node for the specified device."""
label = device.ui_label
dev_label = device.ui_device_label
# determine available methods
methods = [Action(method, device,
self._labels[method].format(label, dev_label),
partial(self._actions[method], device))
for method in self._get_device_methods(device)]
# find the root device:
root = device.parent_object_path
# in this first step leave branches empty
return device.object_path, Device(root, [], device, dev_label, methods)
|
python
|
def _device_node(self, device):
"""Create an empty menu node for the specified device."""
label = device.ui_label
dev_label = device.ui_device_label
# determine available methods
methods = [Action(method, device,
self._labels[method].format(label, dev_label),
partial(self._actions[method], device))
for method in self._get_device_methods(device)]
# find the root device:
root = device.parent_object_path
# in this first step leave branches empty
return device.object_path, Device(root, [], device, dev_label, methods)
|
[
"def",
"_device_node",
"(",
"self",
",",
"device",
")",
":",
"label",
"=",
"device",
".",
"ui_label",
"dev_label",
"=",
"device",
".",
"ui_device_label",
"# determine available methods",
"methods",
"=",
"[",
"Action",
"(",
"method",
",",
"device",
",",
"self",
".",
"_labels",
"[",
"method",
"]",
".",
"format",
"(",
"label",
",",
"dev_label",
")",
",",
"partial",
"(",
"self",
".",
"_actions",
"[",
"method",
"]",
",",
"device",
")",
")",
"for",
"method",
"in",
"self",
".",
"_get_device_methods",
"(",
"device",
")",
"]",
"# find the root device:",
"root",
"=",
"device",
".",
"parent_object_path",
"# in this first step leave branches empty",
"return",
"device",
".",
"object_path",
",",
"Device",
"(",
"root",
",",
"[",
"]",
",",
"device",
",",
"dev_label",
",",
"methods",
")"
] |
Create an empty menu node for the specified device.
|
[
"Create",
"an",
"empty",
"menu",
"node",
"for",
"the",
"specified",
"device",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L829-L841
|
11,304
|
coldfix/udiskie
|
udiskie/common.py
|
samefile
|
def samefile(a: str, b: str) -> bool:
"""Check if two pathes represent the same file."""
try:
return os.path.samefile(a, b)
except OSError:
return os.path.normpath(a) == os.path.normpath(b)
|
python
|
def samefile(a: str, b: str) -> bool:
"""Check if two pathes represent the same file."""
try:
return os.path.samefile(a, b)
except OSError:
return os.path.normpath(a) == os.path.normpath(b)
|
[
"def",
"samefile",
"(",
"a",
":",
"str",
",",
"b",
":",
"str",
")",
"->",
"bool",
":",
"try",
":",
"return",
"os",
".",
"path",
".",
"samefile",
"(",
"a",
",",
"b",
")",
"except",
"OSError",
":",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"a",
")",
"==",
"os",
".",
"path",
".",
"normpath",
"(",
"b",
")"
] |
Check if two pathes represent the same file.
|
[
"Check",
"if",
"two",
"pathes",
"represent",
"the",
"same",
"file",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/common.py#L55-L60
|
11,305
|
coldfix/udiskie
|
udiskie/common.py
|
sameuuid
|
def sameuuid(a: str, b: str) -> bool:
"""Compare two UUIDs."""
return a and b and a.lower() == b.lower()
|
python
|
def sameuuid(a: str, b: str) -> bool:
"""Compare two UUIDs."""
return a and b and a.lower() == b.lower()
|
[
"def",
"sameuuid",
"(",
"a",
":",
"str",
",",
"b",
":",
"str",
")",
"->",
"bool",
":",
"return",
"a",
"and",
"b",
"and",
"a",
".",
"lower",
"(",
")",
"==",
"b",
".",
"lower",
"(",
")"
] |
Compare two UUIDs.
|
[
"Compare",
"two",
"UUIDs",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/common.py#L63-L65
|
11,306
|
coldfix/udiskie
|
udiskie/common.py
|
extend
|
def extend(a: dict, b: dict) -> dict:
"""Merge two dicts and return a new dict. Much like subclassing works."""
res = a.copy()
res.update(b)
return res
|
python
|
def extend(a: dict, b: dict) -> dict:
"""Merge two dicts and return a new dict. Much like subclassing works."""
res = a.copy()
res.update(b)
return res
|
[
"def",
"extend",
"(",
"a",
":",
"dict",
",",
"b",
":",
"dict",
")",
"->",
"dict",
":",
"res",
"=",
"a",
".",
"copy",
"(",
")",
"res",
".",
"update",
"(",
"b",
")",
"return",
"res"
] |
Merge two dicts and return a new dict. Much like subclassing works.
|
[
"Merge",
"two",
"dicts",
"and",
"return",
"a",
"new",
"dict",
".",
"Much",
"like",
"subclassing",
"works",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/common.py#L74-L78
|
11,307
|
coldfix/udiskie
|
udiskie/common.py
|
decode_ay
|
def decode_ay(ay):
"""Convert binary blob from DBus queries to strings."""
if ay is None:
return ''
elif isinstance(ay, str):
return ay
elif isinstance(ay, bytes):
return ay.decode('utf-8')
else:
# dbus.Array([dbus.Byte]) or any similar sequence type:
return bytearray(ay).rstrip(bytearray((0,))).decode('utf-8')
|
python
|
def decode_ay(ay):
"""Convert binary blob from DBus queries to strings."""
if ay is None:
return ''
elif isinstance(ay, str):
return ay
elif isinstance(ay, bytes):
return ay.decode('utf-8')
else:
# dbus.Array([dbus.Byte]) or any similar sequence type:
return bytearray(ay).rstrip(bytearray((0,))).decode('utf-8')
|
[
"def",
"decode_ay",
"(",
"ay",
")",
":",
"if",
"ay",
"is",
"None",
":",
"return",
"''",
"elif",
"isinstance",
"(",
"ay",
",",
"str",
")",
":",
"return",
"ay",
"elif",
"isinstance",
"(",
"ay",
",",
"bytes",
")",
":",
"return",
"ay",
".",
"decode",
"(",
"'utf-8'",
")",
"else",
":",
"# dbus.Array([dbus.Byte]) or any similar sequence type:",
"return",
"bytearray",
"(",
"ay",
")",
".",
"rstrip",
"(",
"bytearray",
"(",
"(",
"0",
",",
")",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")"
] |
Convert binary blob from DBus queries to strings.
|
[
"Convert",
"binary",
"blob",
"from",
"DBus",
"queries",
"to",
"strings",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/common.py#L151-L161
|
11,308
|
coldfix/udiskie
|
udiskie/common.py
|
format_exc
|
def format_exc(*exc_info):
"""Show exception with traceback."""
typ, exc, tb = exc_info or sys.exc_info()
error = traceback.format_exception(typ, exc, tb)
return "".join(error)
|
python
|
def format_exc(*exc_info):
"""Show exception with traceback."""
typ, exc, tb = exc_info or sys.exc_info()
error = traceback.format_exception(typ, exc, tb)
return "".join(error)
|
[
"def",
"format_exc",
"(",
"*",
"exc_info",
")",
":",
"typ",
",",
"exc",
",",
"tb",
"=",
"exc_info",
"or",
"sys",
".",
"exc_info",
"(",
")",
"error",
"=",
"traceback",
".",
"format_exception",
"(",
"typ",
",",
"exc",
",",
"tb",
")",
"return",
"\"\"",
".",
"join",
"(",
"error",
")"
] |
Show exception with traceback.
|
[
"Show",
"exception",
"with",
"traceback",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/common.py#L170-L174
|
11,309
|
coldfix/udiskie
|
udiskie/common.py
|
Emitter.trigger
|
def trigger(self, event, *args):
"""Trigger event by name."""
for handler in self._event_handlers[event]:
handler(*args)
|
python
|
def trigger(self, event, *args):
"""Trigger event by name."""
for handler in self._event_handlers[event]:
handler(*args)
|
[
"def",
"trigger",
"(",
"self",
",",
"event",
",",
"*",
"args",
")",
":",
"for",
"handler",
"in",
"self",
".",
"_event_handlers",
"[",
"event",
"]",
":",
"handler",
"(",
"*",
"args",
")"
] |
Trigger event by name.
|
[
"Trigger",
"event",
"by",
"name",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/common.py#L41-L44
|
11,310
|
coldfix/udiskie
|
udiskie/cli.py
|
Choice._check
|
def _check(self, args):
"""Exit in case of multiple exclusive arguments."""
if sum(bool(args[arg]) for arg in self._mapping) > 1:
raise DocoptExit(_('These options are mutually exclusive: {0}',
', '.join(self._mapping)))
|
python
|
def _check(self, args):
"""Exit in case of multiple exclusive arguments."""
if sum(bool(args[arg]) for arg in self._mapping) > 1:
raise DocoptExit(_('These options are mutually exclusive: {0}',
', '.join(self._mapping)))
|
[
"def",
"_check",
"(",
"self",
",",
"args",
")",
":",
"if",
"sum",
"(",
"bool",
"(",
"args",
"[",
"arg",
"]",
")",
"for",
"arg",
"in",
"self",
".",
"_mapping",
")",
">",
"1",
":",
"raise",
"DocoptExit",
"(",
"_",
"(",
"'These options are mutually exclusive: {0}'",
",",
"', '",
".",
"join",
"(",
"self",
".",
"_mapping",
")",
")",
")"
] |
Exit in case of multiple exclusive arguments.
|
[
"Exit",
"in",
"case",
"of",
"multiple",
"exclusive",
"arguments",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/cli.py#L43-L47
|
11,311
|
coldfix/udiskie
|
udiskie/cli.py
|
_EntryPoint.program_options
|
def program_options(self, args):
"""Get program options from docopt parsed options."""
options = {}
for name, rule in self.option_rules.items():
val = rule(args)
if val is not None:
options[name] = val
return options
|
python
|
def program_options(self, args):
"""Get program options from docopt parsed options."""
options = {}
for name, rule in self.option_rules.items():
val = rule(args)
if val is not None:
options[name] = val
return options
|
[
"def",
"program_options",
"(",
"self",
",",
"args",
")",
":",
"options",
"=",
"{",
"}",
"for",
"name",
",",
"rule",
"in",
"self",
".",
"option_rules",
".",
"items",
"(",
")",
":",
"val",
"=",
"rule",
"(",
"args",
")",
"if",
"val",
"is",
"not",
"None",
":",
"options",
"[",
"name",
"]",
"=",
"val",
"return",
"options"
] |
Get program options from docopt parsed options.
|
[
"Get",
"program",
"options",
"from",
"docopt",
"parsed",
"options",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/cli.py#L176-L183
|
11,312
|
coldfix/udiskie
|
udiskie/cli.py
|
_EntryPoint.run
|
def run(self):
"""Run the main loop. Returns exit code."""
self.exit_code = 1
self.mainloop = GLib.MainLoop()
try:
future = ensure_future(self._start_async_tasks())
future.callbacks.append(self.set_exit_code)
self.mainloop.run()
return self.exit_code
except KeyboardInterrupt:
return 1
|
python
|
def run(self):
"""Run the main loop. Returns exit code."""
self.exit_code = 1
self.mainloop = GLib.MainLoop()
try:
future = ensure_future(self._start_async_tasks())
future.callbacks.append(self.set_exit_code)
self.mainloop.run()
return self.exit_code
except KeyboardInterrupt:
return 1
|
[
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"exit_code",
"=",
"1",
"self",
".",
"mainloop",
"=",
"GLib",
".",
"MainLoop",
"(",
")",
"try",
":",
"future",
"=",
"ensure_future",
"(",
"self",
".",
"_start_async_tasks",
"(",
")",
")",
"future",
".",
"callbacks",
".",
"append",
"(",
"self",
".",
"set_exit_code",
")",
"self",
".",
"mainloop",
".",
"run",
"(",
")",
"return",
"self",
".",
"exit_code",
"except",
"KeyboardInterrupt",
":",
"return",
"1"
] |
Run the main loop. Returns exit code.
|
[
"Run",
"the",
"main",
"loop",
".",
"Returns",
"exit",
"code",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/cli.py#L204-L214
|
11,313
|
coldfix/udiskie
|
udiskie/cli.py
|
_EntryPoint._start_async_tasks
|
async def _start_async_tasks(self):
"""Start asynchronous operations."""
try:
self.udisks = await udiskie.udisks2.Daemon.create()
results = await self._init()
return 0 if all(results) else 1
except Exception:
traceback.print_exc()
return 1
finally:
self.mainloop.quit()
|
python
|
async def _start_async_tasks(self):
"""Start asynchronous operations."""
try:
self.udisks = await udiskie.udisks2.Daemon.create()
results = await self._init()
return 0 if all(results) else 1
except Exception:
traceback.print_exc()
return 1
finally:
self.mainloop.quit()
|
[
"async",
"def",
"_start_async_tasks",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"udisks",
"=",
"await",
"udiskie",
".",
"udisks2",
".",
"Daemon",
".",
"create",
"(",
")",
"results",
"=",
"await",
"self",
".",
"_init",
"(",
")",
"return",
"0",
"if",
"all",
"(",
"results",
")",
"else",
"1",
"except",
"Exception",
":",
"traceback",
".",
"print_exc",
"(",
")",
"return",
"1",
"finally",
":",
"self",
".",
"mainloop",
".",
"quit",
"(",
")"
] |
Start asynchronous operations.
|
[
"Start",
"asynchronous",
"operations",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/cli.py#L219-L229
|
11,314
|
coldfix/udiskie
|
udiskie/automount.py
|
AutoMounter.device_changed
|
def device_changed(self, old_state, new_state):
"""Mount newly mountable devices."""
# udisks2 sometimes adds empty devices and later updates them - which
# makes is_external become true at a time later than device_added:
if (self._mounter.is_addable(new_state)
and not self._mounter.is_addable(old_state)
and not self._mounter.is_removable(old_state)):
self.auto_add(new_state)
|
python
|
def device_changed(self, old_state, new_state):
"""Mount newly mountable devices."""
# udisks2 sometimes adds empty devices and later updates them - which
# makes is_external become true at a time later than device_added:
if (self._mounter.is_addable(new_state)
and not self._mounter.is_addable(old_state)
and not self._mounter.is_removable(old_state)):
self.auto_add(new_state)
|
[
"def",
"device_changed",
"(",
"self",
",",
"old_state",
",",
"new_state",
")",
":",
"# udisks2 sometimes adds empty devices and later updates them - which",
"# makes is_external become true at a time later than device_added:",
"if",
"(",
"self",
".",
"_mounter",
".",
"is_addable",
"(",
"new_state",
")",
"and",
"not",
"self",
".",
"_mounter",
".",
"is_addable",
"(",
"old_state",
")",
"and",
"not",
"self",
".",
"_mounter",
".",
"is_removable",
"(",
"old_state",
")",
")",
":",
"self",
".",
"auto_add",
"(",
"new_state",
")"
] |
Mount newly mountable devices.
|
[
"Mount",
"newly",
"mountable",
"devices",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/automount.py#L41-L48
|
11,315
|
coldfix/udiskie
|
udiskie/dbus.py
|
connect_service
|
async def connect_service(bus_name, object_path, interface):
"""Connect to the service object on DBus, return InterfaceProxy."""
proxy = await proxy_new_for_bus(
Gio.BusType.SYSTEM,
Gio.DBusProxyFlags.DO_NOT_LOAD_PROPERTIES |
Gio.DBusProxyFlags.DO_NOT_CONNECT_SIGNALS,
info=None,
name=bus_name,
object_path=object_path,
interface_name=interface,
)
return InterfaceProxy(proxy)
|
python
|
async def connect_service(bus_name, object_path, interface):
"""Connect to the service object on DBus, return InterfaceProxy."""
proxy = await proxy_new_for_bus(
Gio.BusType.SYSTEM,
Gio.DBusProxyFlags.DO_NOT_LOAD_PROPERTIES |
Gio.DBusProxyFlags.DO_NOT_CONNECT_SIGNALS,
info=None,
name=bus_name,
object_path=object_path,
interface_name=interface,
)
return InterfaceProxy(proxy)
|
[
"async",
"def",
"connect_service",
"(",
"bus_name",
",",
"object_path",
",",
"interface",
")",
":",
"proxy",
"=",
"await",
"proxy_new_for_bus",
"(",
"Gio",
".",
"BusType",
".",
"SYSTEM",
",",
"Gio",
".",
"DBusProxyFlags",
".",
"DO_NOT_LOAD_PROPERTIES",
"|",
"Gio",
".",
"DBusProxyFlags",
".",
"DO_NOT_CONNECT_SIGNALS",
",",
"info",
"=",
"None",
",",
"name",
"=",
"bus_name",
",",
"object_path",
"=",
"object_path",
",",
"interface_name",
"=",
"interface",
",",
")",
"return",
"InterfaceProxy",
"(",
"proxy",
")"
] |
Connect to the service object on DBus, return InterfaceProxy.
|
[
"Connect",
"to",
"the",
"service",
"object",
"on",
"DBus",
"return",
"InterfaceProxy",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/dbus.py#L286-L297
|
11,316
|
coldfix/udiskie
|
udiskie/dbus.py
|
InterfaceProxy.object
|
def object(self):
"""Get an ObjectProxy instanec for the underlying object."""
proxy = self._proxy
return ObjectProxy(proxy.get_connection(),
proxy.get_name(),
proxy.get_object_path())
|
python
|
def object(self):
"""Get an ObjectProxy instanec for the underlying object."""
proxy = self._proxy
return ObjectProxy(proxy.get_connection(),
proxy.get_name(),
proxy.get_object_path())
|
[
"def",
"object",
"(",
"self",
")",
":",
"proxy",
"=",
"self",
".",
"_proxy",
"return",
"ObjectProxy",
"(",
"proxy",
".",
"get_connection",
"(",
")",
",",
"proxy",
".",
"get_name",
"(",
")",
",",
"proxy",
".",
"get_object_path",
"(",
")",
")"
] |
Get an ObjectProxy instanec for the underlying object.
|
[
"Get",
"an",
"ObjectProxy",
"instanec",
"for",
"the",
"underlying",
"object",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/dbus.py#L103-L108
|
11,317
|
coldfix/udiskie
|
udiskie/dbus.py
|
BusProxy.connect
|
def connect(self, interface, event, object_path, handler):
"""
Connect to a DBus signal. If ``object_path`` is None, subscribe for
all objects and invoke the callback with the object_path as its first
argument.
"""
if object_path:
def callback(connection, sender_name, object_path,
interface_name, signal_name, parameters):
return handler(*unpack_variant(parameters))
else:
def callback(connection, sender_name, object_path,
interface_name, signal_name, parameters):
return handler(object_path, *unpack_variant(parameters))
return self.connection.signal_subscribe(
self.bus_name,
interface,
event,
object_path,
None,
Gio.DBusSignalFlags.NONE,
callback,
)
|
python
|
def connect(self, interface, event, object_path, handler):
"""
Connect to a DBus signal. If ``object_path`` is None, subscribe for
all objects and invoke the callback with the object_path as its first
argument.
"""
if object_path:
def callback(connection, sender_name, object_path,
interface_name, signal_name, parameters):
return handler(*unpack_variant(parameters))
else:
def callback(connection, sender_name, object_path,
interface_name, signal_name, parameters):
return handler(object_path, *unpack_variant(parameters))
return self.connection.signal_subscribe(
self.bus_name,
interface,
event,
object_path,
None,
Gio.DBusSignalFlags.NONE,
callback,
)
|
[
"def",
"connect",
"(",
"self",
",",
"interface",
",",
"event",
",",
"object_path",
",",
"handler",
")",
":",
"if",
"object_path",
":",
"def",
"callback",
"(",
"connection",
",",
"sender_name",
",",
"object_path",
",",
"interface_name",
",",
"signal_name",
",",
"parameters",
")",
":",
"return",
"handler",
"(",
"*",
"unpack_variant",
"(",
"parameters",
")",
")",
"else",
":",
"def",
"callback",
"(",
"connection",
",",
"sender_name",
",",
"object_path",
",",
"interface_name",
",",
"signal_name",
",",
"parameters",
")",
":",
"return",
"handler",
"(",
"object_path",
",",
"*",
"unpack_variant",
"(",
"parameters",
")",
")",
"return",
"self",
".",
"connection",
".",
"signal_subscribe",
"(",
"self",
".",
"bus_name",
",",
"interface",
",",
"event",
",",
"object_path",
",",
"None",
",",
"Gio",
".",
"DBusSignalFlags",
".",
"NONE",
",",
"callback",
",",
")"
] |
Connect to a DBus signal. If ``object_path`` is None, subscribe for
all objects and invoke the callback with the object_path as its first
argument.
|
[
"Connect",
"to",
"a",
"DBus",
"signal",
".",
"If",
"object_path",
"is",
"None",
"subscribe",
"for",
"all",
"objects",
"and",
"invoke",
"the",
"callback",
"with",
"the",
"object_path",
"as",
"its",
"first",
"argument",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/dbus.py#L212-L234
|
11,318
|
coldfix/udiskie
|
udiskie/depend.py
|
require_Gtk
|
def require_Gtk(min_version=2):
"""
Make sure Gtk is properly initialized.
:raises RuntimeError: if Gtk can not be properly initialized
"""
if not _in_X:
raise RuntimeError('Not in X session.')
if _has_Gtk < min_version:
raise RuntimeError('Module gi.repository.Gtk not available!')
if _has_Gtk == 2:
logging.getLogger(__name__).warn(
_("Missing runtime dependency GTK 3. Falling back to GTK 2 "
"for password prompt"))
from gi.repository import Gtk
# if we attempt to create any GUI elements with no X server running the
# program will just crash, so let's make a way to catch this case:
if not Gtk.init_check(None)[0]:
raise RuntimeError(_("X server not connected!"))
return Gtk
|
python
|
def require_Gtk(min_version=2):
"""
Make sure Gtk is properly initialized.
:raises RuntimeError: if Gtk can not be properly initialized
"""
if not _in_X:
raise RuntimeError('Not in X session.')
if _has_Gtk < min_version:
raise RuntimeError('Module gi.repository.Gtk not available!')
if _has_Gtk == 2:
logging.getLogger(__name__).warn(
_("Missing runtime dependency GTK 3. Falling back to GTK 2 "
"for password prompt"))
from gi.repository import Gtk
# if we attempt to create any GUI elements with no X server running the
# program will just crash, so let's make a way to catch this case:
if not Gtk.init_check(None)[0]:
raise RuntimeError(_("X server not connected!"))
return Gtk
|
[
"def",
"require_Gtk",
"(",
"min_version",
"=",
"2",
")",
":",
"if",
"not",
"_in_X",
":",
"raise",
"RuntimeError",
"(",
"'Not in X session.'",
")",
"if",
"_has_Gtk",
"<",
"min_version",
":",
"raise",
"RuntimeError",
"(",
"'Module gi.repository.Gtk not available!'",
")",
"if",
"_has_Gtk",
"==",
"2",
":",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"warn",
"(",
"_",
"(",
"\"Missing runtime dependency GTK 3. Falling back to GTK 2 \"",
"\"for password prompt\"",
")",
")",
"from",
"gi",
".",
"repository",
"import",
"Gtk",
"# if we attempt to create any GUI elements with no X server running the",
"# program will just crash, so let's make a way to catch this case:",
"if",
"not",
"Gtk",
".",
"init_check",
"(",
"None",
")",
"[",
"0",
"]",
":",
"raise",
"RuntimeError",
"(",
"_",
"(",
"\"X server not connected!\"",
")",
")",
"return",
"Gtk"
] |
Make sure Gtk is properly initialized.
:raises RuntimeError: if Gtk can not be properly initialized
|
[
"Make",
"sure",
"Gtk",
"is",
"properly",
"initialized",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/depend.py#L38-L57
|
11,319
|
coldfix/udiskie
|
udiskie/locale.py
|
_
|
def _(text, *args, **kwargs):
"""Translate and then and format the text with ``str.format``."""
msg = _t.gettext(text)
if args or kwargs:
return msg.format(*args, **kwargs)
else:
return msg
|
python
|
def _(text, *args, **kwargs):
"""Translate and then and format the text with ``str.format``."""
msg = _t.gettext(text)
if args or kwargs:
return msg.format(*args, **kwargs)
else:
return msg
|
[
"def",
"_",
"(",
"text",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"_t",
".",
"gettext",
"(",
"text",
")",
"if",
"args",
"or",
"kwargs",
":",
"return",
"msg",
".",
"format",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"msg"
] |
Translate and then and format the text with ``str.format``.
|
[
"Translate",
"and",
"then",
"and",
"format",
"the",
"text",
"with",
"str",
".",
"format",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/locale.py#L11-L17
|
11,320
|
coldfix/udiskie
|
udiskie/udisks2.py
|
filter_opt
|
def filter_opt(opt):
"""Remove ``None`` values from a dictionary."""
return {k: GLib.Variant(*v) for k, v in opt.items() if v[1] is not None}
|
python
|
def filter_opt(opt):
"""Remove ``None`` values from a dictionary."""
return {k: GLib.Variant(*v) for k, v in opt.items() if v[1] is not None}
|
[
"def",
"filter_opt",
"(",
"opt",
")",
":",
"return",
"{",
"k",
":",
"GLib",
".",
"Variant",
"(",
"*",
"v",
")",
"for",
"k",
",",
"v",
"in",
"opt",
".",
"items",
"(",
")",
"if",
"v",
"[",
"1",
"]",
"is",
"not",
"None",
"}"
] |
Remove ``None`` values from a dictionary.
|
[
"Remove",
"None",
"values",
"from",
"a",
"dictionary",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L43-L45
|
11,321
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Device.eject
|
def eject(self, auth_no_user_interaction=None):
"""Eject media from the device."""
return self._assocdrive._M.Drive.Eject(
'(a{sv})',
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
)
|
python
|
def eject(self, auth_no_user_interaction=None):
"""Eject media from the device."""
return self._assocdrive._M.Drive.Eject(
'(a{sv})',
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
)
|
[
"def",
"eject",
"(",
"self",
",",
"auth_no_user_interaction",
"=",
"None",
")",
":",
"return",
"self",
".",
"_assocdrive",
".",
"_M",
".",
"Drive",
".",
"Eject",
"(",
"'(a{sv})'",
",",
"filter_opt",
"(",
"{",
"'auth.no_user_interaction'",
":",
"(",
"'b'",
",",
"auth_no_user_interaction",
")",
",",
"}",
")",
")"
] |
Eject media from the device.
|
[
"Eject",
"media",
"from",
"the",
"device",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L232-L239
|
11,322
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Device.device_id
|
def device_id(self):
"""
Return a unique and persistent identifier for the device.
This is the basename (last path component) of the symlink in
`/dev/disk/by-id/`.
"""
if self.is_block:
for filename in self._P.Block.Symlinks:
parts = decode_ay(filename).split('/')
if parts[-2] == 'by-id':
return parts[-1]
elif self.is_drive:
return self._assocdrive._P.Drive.Id
return ''
|
python
|
def device_id(self):
"""
Return a unique and persistent identifier for the device.
This is the basename (last path component) of the symlink in
`/dev/disk/by-id/`.
"""
if self.is_block:
for filename in self._P.Block.Symlinks:
parts = decode_ay(filename).split('/')
if parts[-2] == 'by-id':
return parts[-1]
elif self.is_drive:
return self._assocdrive._P.Drive.Id
return ''
|
[
"def",
"device_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_block",
":",
"for",
"filename",
"in",
"self",
".",
"_P",
".",
"Block",
".",
"Symlinks",
":",
"parts",
"=",
"decode_ay",
"(",
"filename",
")",
".",
"split",
"(",
"'/'",
")",
"if",
"parts",
"[",
"-",
"2",
"]",
"==",
"'by-id'",
":",
"return",
"parts",
"[",
"-",
"1",
"]",
"elif",
"self",
".",
"is_drive",
":",
"return",
"self",
".",
"_assocdrive",
".",
"_P",
".",
"Drive",
".",
"Id",
"return",
"''"
] |
Return a unique and persistent identifier for the device.
This is the basename (last path component) of the symlink in
`/dev/disk/by-id/`.
|
[
"Return",
"a",
"unique",
"and",
"persistent",
"identifier",
"for",
"the",
"device",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L286-L300
|
11,323
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Device.is_external
|
def is_external(self):
"""Check if the device is external."""
# NOTE: Checking for equality HintSystem==False returns False if the
# property is resolved to a None value (interface not available).
if self._P.Block.HintSystem == False: # noqa: E712
return True
# NOTE: udisks2 seems to guess incorrectly in some cases. This
# leads to HintSystem=True for unlocked devices. In order to show
# the device anyway, it needs to be recursively checked if any
# parent device is recognized as external.
if self.is_luks_cleartext and self.luks_cleartext_slave.is_external:
return True
if self.is_partition and self.partition_slave.is_external:
return True
return False
|
python
|
def is_external(self):
"""Check if the device is external."""
# NOTE: Checking for equality HintSystem==False returns False if the
# property is resolved to a None value (interface not available).
if self._P.Block.HintSystem == False: # noqa: E712
return True
# NOTE: udisks2 seems to guess incorrectly in some cases. This
# leads to HintSystem=True for unlocked devices. In order to show
# the device anyway, it needs to be recursively checked if any
# parent device is recognized as external.
if self.is_luks_cleartext and self.luks_cleartext_slave.is_external:
return True
if self.is_partition and self.partition_slave.is_external:
return True
return False
|
[
"def",
"is_external",
"(",
"self",
")",
":",
"# NOTE: Checking for equality HintSystem==False returns False if the",
"# property is resolved to a None value (interface not available).",
"if",
"self",
".",
"_P",
".",
"Block",
".",
"HintSystem",
"==",
"False",
":",
"# noqa: E712",
"return",
"True",
"# NOTE: udisks2 seems to guess incorrectly in some cases. This",
"# leads to HintSystem=True for unlocked devices. In order to show",
"# the device anyway, it needs to be recursively checked if any",
"# parent device is recognized as external.",
"if",
"self",
".",
"is_luks_cleartext",
"and",
"self",
".",
"luks_cleartext_slave",
".",
"is_external",
":",
"return",
"True",
"if",
"self",
".",
"is_partition",
"and",
"self",
".",
"partition_slave",
".",
"is_external",
":",
"return",
"True",
"return",
"False"
] |
Check if the device is external.
|
[
"Check",
"if",
"the",
"device",
"is",
"external",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L335-L349
|
11,324
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Device.drive
|
def drive(self):
"""Get wrapper to the drive containing this device."""
if self.is_drive:
return self
cleartext = self.luks_cleartext_slave
if cleartext:
return cleartext.drive
if self.is_block:
return self._daemon[self._P.Block.Drive]
return None
|
python
|
def drive(self):
"""Get wrapper to the drive containing this device."""
if self.is_drive:
return self
cleartext = self.luks_cleartext_slave
if cleartext:
return cleartext.drive
if self.is_block:
return self._daemon[self._P.Block.Drive]
return None
|
[
"def",
"drive",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_drive",
":",
"return",
"self",
"cleartext",
"=",
"self",
".",
"luks_cleartext_slave",
"if",
"cleartext",
":",
"return",
"cleartext",
".",
"drive",
"if",
"self",
".",
"is_block",
":",
"return",
"self",
".",
"_daemon",
"[",
"self",
".",
"_P",
".",
"Block",
".",
"Drive",
"]",
"return",
"None"
] |
Get wrapper to the drive containing this device.
|
[
"Get",
"wrapper",
"to",
"the",
"drive",
"containing",
"this",
"device",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L357-L366
|
11,325
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Device.root
|
def root(self):
"""Get the top level block device in the ancestry of this device."""
drive = self.drive
for device in self._daemon:
if device.is_drive:
continue
if device.is_toplevel and device.drive == drive:
return device
return None
|
python
|
def root(self):
"""Get the top level block device in the ancestry of this device."""
drive = self.drive
for device in self._daemon:
if device.is_drive:
continue
if device.is_toplevel and device.drive == drive:
return device
return None
|
[
"def",
"root",
"(",
"self",
")",
":",
"drive",
"=",
"self",
".",
"drive",
"for",
"device",
"in",
"self",
".",
"_daemon",
":",
"if",
"device",
".",
"is_drive",
":",
"continue",
"if",
"device",
".",
"is_toplevel",
"and",
"device",
".",
"drive",
"==",
"drive",
":",
"return",
"device",
"return",
"None"
] |
Get the top level block device in the ancestry of this device.
|
[
"Get",
"the",
"top",
"level",
"block",
"device",
"in",
"the",
"ancestry",
"of",
"this",
"device",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L369-L377
|
11,326
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Device.symlinks
|
def symlinks(self):
"""Known symlinks of the block device."""
if not self._P.Block.Symlinks:
return []
return [decode_ay(path) for path in self._P.Block.Symlinks]
|
python
|
def symlinks(self):
"""Known symlinks of the block device."""
if not self._P.Block.Symlinks:
return []
return [decode_ay(path) for path in self._P.Block.Symlinks]
|
[
"def",
"symlinks",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_P",
".",
"Block",
".",
"Symlinks",
":",
"return",
"[",
"]",
"return",
"[",
"decode_ay",
"(",
"path",
")",
"for",
"path",
"in",
"self",
".",
"_P",
".",
"Block",
".",
"Symlinks",
"]"
] |
Known symlinks of the block device.
|
[
"Known",
"symlinks",
"of",
"the",
"block",
"device",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L395-L399
|
11,327
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Device.mount
|
def mount(self,
fstype=None,
options=None,
auth_no_user_interaction=None):
"""Mount filesystem."""
return self._M.Filesystem.Mount(
'(a{sv})',
filter_opt({
'fstype': ('s', fstype),
'options': ('s', ','.join(options or [])),
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
)
|
python
|
def mount(self,
fstype=None,
options=None,
auth_no_user_interaction=None):
"""Mount filesystem."""
return self._M.Filesystem.Mount(
'(a{sv})',
filter_opt({
'fstype': ('s', fstype),
'options': ('s', ','.join(options or [])),
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
)
|
[
"def",
"mount",
"(",
"self",
",",
"fstype",
"=",
"None",
",",
"options",
"=",
"None",
",",
"auth_no_user_interaction",
"=",
"None",
")",
":",
"return",
"self",
".",
"_M",
".",
"Filesystem",
".",
"Mount",
"(",
"'(a{sv})'",
",",
"filter_opt",
"(",
"{",
"'fstype'",
":",
"(",
"'s'",
",",
"fstype",
")",
",",
"'options'",
":",
"(",
"'s'",
",",
"','",
".",
"join",
"(",
"options",
"or",
"[",
"]",
")",
")",
",",
"'auth.no_user_interaction'",
":",
"(",
"'b'",
",",
"auth_no_user_interaction",
")",
",",
"}",
")",
")"
] |
Mount filesystem.
|
[
"Mount",
"filesystem",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L432-L444
|
11,328
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Device.unmount
|
def unmount(self, force=None, auth_no_user_interaction=None):
"""Unmount filesystem."""
return self._M.Filesystem.Unmount(
'(a{sv})',
filter_opt({
'force': ('b', force),
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
)
|
python
|
def unmount(self, force=None, auth_no_user_interaction=None):
"""Unmount filesystem."""
return self._M.Filesystem.Unmount(
'(a{sv})',
filter_opt({
'force': ('b', force),
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
)
|
[
"def",
"unmount",
"(",
"self",
",",
"force",
"=",
"None",
",",
"auth_no_user_interaction",
"=",
"None",
")",
":",
"return",
"self",
".",
"_M",
".",
"Filesystem",
".",
"Unmount",
"(",
"'(a{sv})'",
",",
"filter_opt",
"(",
"{",
"'force'",
":",
"(",
"'b'",
",",
"force",
")",
",",
"'auth.no_user_interaction'",
":",
"(",
"'b'",
",",
"auth_no_user_interaction",
")",
",",
"}",
")",
")"
] |
Unmount filesystem.
|
[
"Unmount",
"filesystem",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L446-L454
|
11,329
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Device.luks_cleartext_holder
|
def luks_cleartext_holder(self):
"""Get wrapper to the unlocked luks cleartext device."""
if not self.is_luks:
return None
for device in self._daemon:
if device.luks_cleartext_slave == self:
return device
return None
|
python
|
def luks_cleartext_holder(self):
"""Get wrapper to the unlocked luks cleartext device."""
if not self.is_luks:
return None
for device in self._daemon:
if device.luks_cleartext_slave == self:
return device
return None
|
[
"def",
"luks_cleartext_holder",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_luks",
":",
"return",
"None",
"for",
"device",
"in",
"self",
".",
"_daemon",
":",
"if",
"device",
".",
"luks_cleartext_slave",
"==",
"self",
":",
"return",
"device",
"return",
"None"
] |
Get wrapper to the unlocked luks cleartext device.
|
[
"Get",
"wrapper",
"to",
"the",
"unlocked",
"luks",
"cleartext",
"device",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L462-L469
|
11,330
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Device.unlock
|
def unlock(self, password, auth_no_user_interaction=None):
"""Unlock Luks device."""
return self._M.Encrypted.Unlock(
'(sa{sv})',
password,
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
)
|
python
|
def unlock(self, password, auth_no_user_interaction=None):
"""Unlock Luks device."""
return self._M.Encrypted.Unlock(
'(sa{sv})',
password,
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
)
|
[
"def",
"unlock",
"(",
"self",
",",
"password",
",",
"auth_no_user_interaction",
"=",
"None",
")",
":",
"return",
"self",
".",
"_M",
".",
"Encrypted",
".",
"Unlock",
"(",
"'(sa{sv})'",
",",
"password",
",",
"filter_opt",
"(",
"{",
"'auth.no_user_interaction'",
":",
"(",
"'b'",
",",
"auth_no_user_interaction",
")",
",",
"}",
")",
")"
] |
Unlock Luks device.
|
[
"Unlock",
"Luks",
"device",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L477-L485
|
11,331
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Device.set_autoclear
|
def set_autoclear(self, value, auth_no_user_interaction=None):
"""Set autoclear flag for loop partition."""
return self._M.Loop.SetAutoclear(
'(ba{sv})',
value,
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
)
|
python
|
def set_autoclear(self, value, auth_no_user_interaction=None):
"""Set autoclear flag for loop partition."""
return self._M.Loop.SetAutoclear(
'(ba{sv})',
value,
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
)
|
[
"def",
"set_autoclear",
"(",
"self",
",",
"value",
",",
"auth_no_user_interaction",
"=",
"None",
")",
":",
"return",
"self",
".",
"_M",
".",
"Loop",
".",
"SetAutoclear",
"(",
"'(ba{sv})'",
",",
"value",
",",
"filter_opt",
"(",
"{",
"'auth.no_user_interaction'",
":",
"(",
"'b'",
",",
"auth_no_user_interaction",
")",
",",
"}",
")",
")"
] |
Set autoclear flag for loop partition.
|
[
"Set",
"autoclear",
"flag",
"for",
"loop",
"partition",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L532-L540
|
11,332
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Device.is_file
|
def is_file(self, path):
"""Comparison by mount and device file path."""
return (samefile(path, self.device_file) or
samefile(path, self.loop_file) or
any(samefile(path, mp) for mp in self.mount_paths) or
sameuuid(path, self.id_uuid) or
sameuuid(path, self.partition_uuid))
|
python
|
def is_file(self, path):
"""Comparison by mount and device file path."""
return (samefile(path, self.device_file) or
samefile(path, self.loop_file) or
any(samefile(path, mp) for mp in self.mount_paths) or
sameuuid(path, self.id_uuid) or
sameuuid(path, self.partition_uuid))
|
[
"def",
"is_file",
"(",
"self",
",",
"path",
")",
":",
"return",
"(",
"samefile",
"(",
"path",
",",
"self",
".",
"device_file",
")",
"or",
"samefile",
"(",
"path",
",",
"self",
".",
"loop_file",
")",
"or",
"any",
"(",
"samefile",
"(",
"path",
",",
"mp",
")",
"for",
"mp",
"in",
"self",
".",
"mount_paths",
")",
"or",
"sameuuid",
"(",
"path",
",",
"self",
".",
"id_uuid",
")",
"or",
"sameuuid",
"(",
"path",
",",
"self",
".",
"partition_uuid",
")",
")"
] |
Comparison by mount and device file path.
|
[
"Comparison",
"by",
"mount",
"and",
"device",
"file",
"path",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L546-L552
|
11,333
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Device.in_use
|
def in_use(self):
"""Check whether this device is in use, i.e. mounted or unlocked."""
if self.is_mounted or self.is_unlocked:
return True
if self.is_partition_table:
for device in self._daemon:
if device.partition_slave == self and device.in_use:
return True
return False
|
python
|
def in_use(self):
"""Check whether this device is in use, i.e. mounted or unlocked."""
if self.is_mounted or self.is_unlocked:
return True
if self.is_partition_table:
for device in self._daemon:
if device.partition_slave == self and device.in_use:
return True
return False
|
[
"def",
"in_use",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_mounted",
"or",
"self",
".",
"is_unlocked",
":",
"return",
"True",
"if",
"self",
".",
"is_partition_table",
":",
"for",
"device",
"in",
"self",
".",
"_daemon",
":",
"if",
"device",
".",
"partition_slave",
"==",
"self",
"and",
"device",
".",
"in_use",
":",
"return",
"True",
"return",
"False"
] |
Check whether this device is in use, i.e. mounted or unlocked.
|
[
"Check",
"whether",
"this",
"device",
"is",
"in",
"use",
"i",
".",
"e",
".",
"mounted",
"or",
"unlocked",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L569-L577
|
11,334
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Device.ui_label
|
def ui_label(self):
"""UI string identifying the partition if possible."""
return ': '.join(filter(None, [
self.ui_device_presentation,
self.ui_id_label or self.ui_id_uuid or self.drive_label
]))
|
python
|
def ui_label(self):
"""UI string identifying the partition if possible."""
return ': '.join(filter(None, [
self.ui_device_presentation,
self.ui_id_label or self.ui_id_uuid or self.drive_label
]))
|
[
"def",
"ui_label",
"(",
"self",
")",
":",
"return",
"': '",
".",
"join",
"(",
"filter",
"(",
"None",
",",
"[",
"self",
".",
"ui_device_presentation",
",",
"self",
".",
"ui_id_label",
"or",
"self",
".",
"ui_id_uuid",
"or",
"self",
".",
"drive_label",
"]",
")",
")"
] |
UI string identifying the partition if possible.
|
[
"UI",
"string",
"identifying",
"the",
"partition",
"if",
"possible",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L595-L600
|
11,335
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Daemon.find
|
def find(self, path):
"""
Get a device proxy by device name or any mount path of the device.
This searches through all accessible devices and compares device
path as well as mount pathes.
"""
if isinstance(path, Device):
return path
for device in self:
if device.is_file(path):
self._log.debug(_('found device owning "{0}": "{1}"',
path, device))
return device
raise FileNotFoundError(_('no device found owning "{0}"', path))
|
python
|
def find(self, path):
"""
Get a device proxy by device name or any mount path of the device.
This searches through all accessible devices and compares device
path as well as mount pathes.
"""
if isinstance(path, Device):
return path
for device in self:
if device.is_file(path):
self._log.debug(_('found device owning "{0}": "{1}"',
path, device))
return device
raise FileNotFoundError(_('no device found owning "{0}"', path))
|
[
"def",
"find",
"(",
"self",
",",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"Device",
")",
":",
"return",
"path",
"for",
"device",
"in",
"self",
":",
"if",
"device",
".",
"is_file",
"(",
"path",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'found device owning \"{0}\": \"{1}\"'",
",",
"path",
",",
"device",
")",
")",
"return",
"device",
"raise",
"FileNotFoundError",
"(",
"_",
"(",
"'no device found owning \"{0}\"'",
",",
"path",
")",
")"
] |
Get a device proxy by device name or any mount path of the device.
This searches through all accessible devices and compares device
path as well as mount pathes.
|
[
"Get",
"a",
"device",
"proxy",
"by",
"device",
"name",
"or",
"any",
"mount",
"path",
"of",
"the",
"device",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L651-L665
|
11,336
|
coldfix/udiskie
|
udiskie/udisks2.py
|
Daemon.get
|
def get(self, object_path, interfaces_and_properties=None):
"""Create a Device instance from object path."""
# check this before creating the DBus object for more
# controlled behaviour:
if not interfaces_and_properties:
interfaces_and_properties = self._objects.get(object_path)
if not interfaces_and_properties:
return None
property_hub = PropertyHub(interfaces_and_properties)
method_hub = MethodHub(
self._proxy.object.bus.get_object(object_path))
return Device(self, object_path, property_hub, method_hub)
|
python
|
def get(self, object_path, interfaces_and_properties=None):
"""Create a Device instance from object path."""
# check this before creating the DBus object for more
# controlled behaviour:
if not interfaces_and_properties:
interfaces_and_properties = self._objects.get(object_path)
if not interfaces_and_properties:
return None
property_hub = PropertyHub(interfaces_and_properties)
method_hub = MethodHub(
self._proxy.object.bus.get_object(object_path))
return Device(self, object_path, property_hub, method_hub)
|
[
"def",
"get",
"(",
"self",
",",
"object_path",
",",
"interfaces_and_properties",
"=",
"None",
")",
":",
"# check this before creating the DBus object for more",
"# controlled behaviour:",
"if",
"not",
"interfaces_and_properties",
":",
"interfaces_and_properties",
"=",
"self",
".",
"_objects",
".",
"get",
"(",
"object_path",
")",
"if",
"not",
"interfaces_and_properties",
":",
"return",
"None",
"property_hub",
"=",
"PropertyHub",
"(",
"interfaces_and_properties",
")",
"method_hub",
"=",
"MethodHub",
"(",
"self",
".",
"_proxy",
".",
"object",
".",
"bus",
".",
"get_object",
"(",
"object_path",
")",
")",
"return",
"Device",
"(",
"self",
",",
"object_path",
",",
"property_hub",
",",
"method_hub",
")"
] |
Create a Device instance from object path.
|
[
"Create",
"a",
"Device",
"instance",
"from",
"object",
"path",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L754-L765
|
11,337
|
coldfix/udiskie
|
udiskie/notify.py
|
Notify.device_mounted
|
def device_mounted(self, device):
"""Show mount notification for specified device object."""
if not self._mounter.is_handleable(device):
return
browse_action = ('browse', _('Browse directory'),
self._mounter.browse, device)
terminal_action = ('terminal', _('Open terminal'),
self._mounter.terminal, device)
self._show_notification(
'device_mounted',
_('Device mounted'),
_('{0.ui_label} mounted on {0.mount_paths[0]}', device),
device.icon_name,
self._mounter._browser and browse_action,
self._mounter._terminal and terminal_action)
|
python
|
def device_mounted(self, device):
"""Show mount notification for specified device object."""
if not self._mounter.is_handleable(device):
return
browse_action = ('browse', _('Browse directory'),
self._mounter.browse, device)
terminal_action = ('terminal', _('Open terminal'),
self._mounter.terminal, device)
self._show_notification(
'device_mounted',
_('Device mounted'),
_('{0.ui_label} mounted on {0.mount_paths[0]}', device),
device.icon_name,
self._mounter._browser and browse_action,
self._mounter._terminal and terminal_action)
|
[
"def",
"device_mounted",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"browse_action",
"=",
"(",
"'browse'",
",",
"_",
"(",
"'Browse directory'",
")",
",",
"self",
".",
"_mounter",
".",
"browse",
",",
"device",
")",
"terminal_action",
"=",
"(",
"'terminal'",
",",
"_",
"(",
"'Open terminal'",
")",
",",
"self",
".",
"_mounter",
".",
"terminal",
",",
"device",
")",
"self",
".",
"_show_notification",
"(",
"'device_mounted'",
",",
"_",
"(",
"'Device mounted'",
")",
",",
"_",
"(",
"'{0.ui_label} mounted on {0.mount_paths[0]}'",
",",
"device",
")",
",",
"device",
".",
"icon_name",
",",
"self",
".",
"_mounter",
".",
"_browser",
"and",
"browse_action",
",",
"self",
".",
"_mounter",
".",
"_terminal",
"and",
"terminal_action",
")"
] |
Show mount notification for specified device object.
|
[
"Show",
"mount",
"notification",
"for",
"specified",
"device",
"object",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L58-L72
|
11,338
|
coldfix/udiskie
|
udiskie/notify.py
|
Notify.device_unmounted
|
def device_unmounted(self, device):
"""Show unmount notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_unmounted',
_('Device unmounted'),
_('{0.ui_label} unmounted', device),
device.icon_name)
|
python
|
def device_unmounted(self, device):
"""Show unmount notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_unmounted',
_('Device unmounted'),
_('{0.ui_label} unmounted', device),
device.icon_name)
|
[
"def",
"device_unmounted",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"self",
".",
"_show_notification",
"(",
"'device_unmounted'",
",",
"_",
"(",
"'Device unmounted'",
")",
",",
"_",
"(",
"'{0.ui_label} unmounted'",
",",
"device",
")",
",",
"device",
".",
"icon_name",
")"
] |
Show unmount notification for specified device object.
|
[
"Show",
"unmount",
"notification",
"for",
"specified",
"device",
"object",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L74-L82
|
11,339
|
coldfix/udiskie
|
udiskie/notify.py
|
Notify.device_locked
|
def device_locked(self, device):
"""Show lock notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_locked',
_('Device locked'),
_('{0.device_presentation} locked', device),
device.icon_name)
|
python
|
def device_locked(self, device):
"""Show lock notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_locked',
_('Device locked'),
_('{0.device_presentation} locked', device),
device.icon_name)
|
[
"def",
"device_locked",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"self",
".",
"_show_notification",
"(",
"'device_locked'",
",",
"_",
"(",
"'Device locked'",
")",
",",
"_",
"(",
"'{0.device_presentation} locked'",
",",
"device",
")",
",",
"device",
".",
"icon_name",
")"
] |
Show lock notification for specified device object.
|
[
"Show",
"lock",
"notification",
"for",
"specified",
"device",
"object",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L84-L92
|
11,340
|
coldfix/udiskie
|
udiskie/notify.py
|
Notify.device_unlocked
|
def device_unlocked(self, device):
"""Show unlock notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_unlocked',
_('Device unlocked'),
_('{0.device_presentation} unlocked', device),
device.icon_name)
|
python
|
def device_unlocked(self, device):
"""Show unlock notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_unlocked',
_('Device unlocked'),
_('{0.device_presentation} unlocked', device),
device.icon_name)
|
[
"def",
"device_unlocked",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"self",
".",
"_show_notification",
"(",
"'device_unlocked'",
",",
"_",
"(",
"'Device unlocked'",
")",
",",
"_",
"(",
"'{0.device_presentation} unlocked'",
",",
"device",
")",
",",
"device",
".",
"icon_name",
")"
] |
Show unlock notification for specified device object.
|
[
"Show",
"unlock",
"notification",
"for",
"specified",
"device",
"object",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L94-L102
|
11,341
|
coldfix/udiskie
|
udiskie/notify.py
|
Notify.device_added
|
def device_added(self, device):
"""Show discovery notification for specified device object."""
if not self._mounter.is_handleable(device):
return
if self._has_actions('device_added'):
# wait for partitions etc to be reported to udiskie, otherwise we
# can't discover the actions
GLib.timeout_add(500, self._device_added, device)
else:
self._device_added(device)
|
python
|
def device_added(self, device):
"""Show discovery notification for specified device object."""
if not self._mounter.is_handleable(device):
return
if self._has_actions('device_added'):
# wait for partitions etc to be reported to udiskie, otherwise we
# can't discover the actions
GLib.timeout_add(500, self._device_added, device)
else:
self._device_added(device)
|
[
"def",
"device_added",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"if",
"self",
".",
"_has_actions",
"(",
"'device_added'",
")",
":",
"# wait for partitions etc to be reported to udiskie, otherwise we",
"# can't discover the actions",
"GLib",
".",
"timeout_add",
"(",
"500",
",",
"self",
".",
"_device_added",
",",
"device",
")",
"else",
":",
"self",
".",
"_device_added",
"(",
"device",
")"
] |
Show discovery notification for specified device object.
|
[
"Show",
"discovery",
"notification",
"for",
"specified",
"device",
"object",
"."
] |
804c9d27df6f7361fec3097c432398f2d702f911
|
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L104-L113
|
11,342
|
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
|
11,343
|
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
|
11,344
|
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
|
11,345
|
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
|
11,346
|
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
|
11,347
|
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
|
11,348
|
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
|
11,349
|
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
|
11,350
|
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
|
11,351
|
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
|
11,352
|
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
|
11,353
|
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
|
11,354
|
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
|
11,355
|
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
|
11,356
|
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
|
11,357
|
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
|
11,358
|
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
|
11,359
|
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
|
11,360
|
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
|
11,361
|
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
|
11,362
|
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
|
11,363
|
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
|
11,364
|
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
|
11,365
|
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
|
11,366
|
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
|
11,367
|
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
|
11,368
|
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
|
11,369
|
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
|
11,370
|
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
|
11,371
|
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
|
11,372
|
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
|
11,373
|
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
|
11,374
|
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
|
11,375
|
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
|
11,376
|
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
|
11,377
|
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
|
11,378
|
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
|
11,379
|
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
|
11,380
|
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
|
11,381
|
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
|
11,382
|
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
|
11,383
|
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
|
11,384
|
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
|
11,385
|
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
|
11,386
|
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
|
11,387
|
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
|
11,388
|
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
|
11,389
|
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
|
11,390
|
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
|
11,391
|
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
|
11,392
|
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
|
11,393
|
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
|
11,394
|
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
|
11,395
|
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
|
11,396
|
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
|
11,397
|
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
|
11,398
|
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
|
11,399
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.