Use pyupgrade with --py36-plus param.

This commit is contained in:
grossmj committed 2021-04-13 18:37:58 +09:30
1 parent a9eb035b7d
commit f928738bd5
235 files changed
+1501 -1638

No files matched your search

+1 -1
View File
@@ -60,7 +60,7 @@ def parse_version(version):
"""
release_type_found = False
version_infos = re.split('(\.|[a-z]+)', version)
version_infos = re.split(r'(\.|[a-z]+)', version)
version = []
for info in version_infos:
if info == '.' or len(info) == 0:
+1 -2
View File
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 GNS3 Technologies Inc.
#
@@ -38,7 +37,7 @@ def get_next_application_id(projects, computes):
if project.status == "opened":
nodes.extend(list(project.nodes.values()))
used = set([n.properties["application_id"] for n in nodes if n.node_type == "iou" and n.compute.id in computes])
used = {n.properties["application_id"] for n in nodes if n.node_type == "iou" and n.compute.id in computes}
pool = set(range(1, 512))
try:
application_id = (pool - used).pop()
-1
View File
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 GNS3 Technologies Inc.
#
+1 -1
View File
@@ -56,7 +56,7 @@ def _get_compressor(compress_type):
return None
class PointerIO(object):
class PointerIO:
def __init__(self, mode='wb'):
if mode not in ('wb', ):
+2 -2
View File
@@ -121,7 +121,7 @@ class EmbedShell:
found = True
break
if not found:
res = ('Command not found {}\n'.format(cmd[0]) + (await self.help()))
res = (f'Command not found {cmd[0]}\n' + (await self.help()))
return res
async def run(self):
@@ -196,7 +196,7 @@ class UnstoppableEventLoop(EventLoop):
class ShellConnection(TelnetConnection):
def __init__(self, reader, writer, shell, window_size_changed_callback, loop):
super(ShellConnection, self).__init__(reader, writer, window_size_changed_callback)
super().__init__(reader, writer, window_size_changed_callback)
self._shell = shell
self._loop = loop
self._cli = None
+3 -5
View File
@@ -4,12 +4,10 @@ Parser for VT100 input stream.
# Copied from prompt_toolkit/terminal/vt100_input.py due to dependency on termios (which is not available on Windows)
from __future__ import unicode_literals
import re
import six
from six.moves import range
from prompt_toolkit.keys import Keys
from prompt_toolkit.key_binding.input_processor import KeyPress
@@ -41,7 +39,7 @@ _cpr_response_prefix_re = re.compile('^' + re.escape('\x1b[') + r'[\d;]*\Z')
_mouse_event_prefix_re = re.compile('^' + re.escape('\x1b[') + r'(<?[\d;]*|M.{0,2})\Z')
class _Flush(object):
class _Flush:
""" Helper object to indicate flush operation to the parser. """
pass
@@ -217,7 +215,7 @@ class _IsPrefixOfLongerMatchCache(dict):
_IS_PREFIX_OF_LONGER_MATCH_CACHE = _IsPrefixOfLongerMatchCache()
class InputStream(object):
class InputStream:
"""
Parser for VT100 input stream.
@@ -345,7 +343,7 @@ class InputStream(object):
:param data: Input string (unicode).
"""
assert isinstance(data, six.text_type)
assert isinstance(data, str)
if _DEBUG_RENDERER_INPUT:
self.LOG.write(repr(data).encode('utf-8') + b'\n')
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 GNS3 Technologies Inc.
#
+3 -3
View File
@@ -102,7 +102,7 @@ async def _asyncio_open_serial_windows(path):
try:
await wait_for_named_pipe_creation(path)
except asyncio.TimeoutError:
raise NodeError('Pipe file "{}" is missing'.format(path))
raise NodeError(f'Pipe file "{path}" is missing')
return WindowsPipe(path)
@@ -117,13 +117,13 @@ async def _asyncio_open_serial_unix(path):
# wait for VM to create the pipe file.
await wait_for_file_creation(path)
except asyncio.TimeoutError:
raise NodeError('Pipe file "{}" is missing'.format(path))
raise NodeError(f'Pipe file "{path}" is missing')
output = SerialReaderWriterProtocol()
try:
await asyncio.get_event_loop().create_unix_connection(lambda: output, path)
except ConnectionRefusedError:
raise NodeError('Can\'t open pipe file "{}"'.format(path))
raise NodeError(f'Can\'t open pipe file "{path}"')
return output
+9 -10
View File
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 GNS3 Technologies Inc.
#
@@ -58,7 +57,7 @@ LINEMO = 34 # Line Mode
READ_SIZE = 1024
class TelnetConnection(object):
class TelnetConnection:
"""Default implementation of telnet connection which may but may not be used."""
def __init__(self, reader, writer, window_size_changed_callback=None):
self.is_closing = False
@@ -310,7 +309,7 @@ class AsyncioTelnetServer:
command, payload = data[0], data[1:]
if command == NAWS:
if len(payload) == 4:
columns, rows = struct.unpack(str('!HH'), bytes(payload))
columns, rows = struct.unpack('!HH', bytes(payload))
await connection.window_size_changed(columns, rows)
else:
log.warning('Wrong number of NAWS bytes')
@@ -358,7 +357,7 @@ class AsyncioTelnetServer:
pass
else:
log.debug("Unhandled telnet command: "
"{0:#x} {1:#x}".format(*iac_cmd))
"{:#x} {:#x}".format(*iac_cmd))
elif iac_cmd[1] == SB: # starts negotiation commands
negotiation = []
for pos in range(2, self.MAX_NEGOTIATION_READ):
@@ -383,28 +382,28 @@ class AsyncioTelnetServer:
if iac_cmd[1] == DO:
if iac_cmd[2] not in [ECHO, SGA, BINARY]:
network_writer.write(bytes([IAC, WONT, iac_cmd[2]]))
log.debug("Telnet WON'T {:#x}".format(iac_cmd[2]))
log.debug(f"Telnet WON'T {iac_cmd[2]:#x}")
else:
if iac_cmd[2] == SGA:
if self._binary:
network_writer.write(bytes([IAC, WILL, iac_cmd[2]]))
else:
network_writer.write(bytes([IAC, WONT, iac_cmd[2]]))
log.debug("Telnet WON'T {:#x}".format(iac_cmd[2]))
log.debug(f"Telnet WON'T {iac_cmd[2]:#x}")
elif iac_cmd[1] == DONT:
log.debug("Unhandled DONT telnet command: "
"{0:#x} {1:#x} {2:#x}".format(*iac_cmd))
"{:#x} {:#x} {:#x}".format(*iac_cmd))
elif iac_cmd[1] == WILL:
if iac_cmd[2] not in [BINARY, NAWS]:
log.debug("Unhandled WILL telnet command: "
"{0:#x} {1:#x} {2:#x}".format(*iac_cmd))
"{:#x} {:#x} {:#x}".format(*iac_cmd))
elif iac_cmd[1] == WONT:
log.debug("Unhandled WONT telnet command: "
"{0:#x} {1:#x} {2:#x}".format(*iac_cmd))
"{:#x} {:#x} {:#x}".format(*iac_cmd))
else:
log.debug("Unhandled telnet command: "
"{0:#x} {1:#x} {2:#x}".format(*iac_cmd))
"{:#x} {:#x} {:#x}".format(*iac_cmd))
# Remove the entire TELNET command from the buffer
buf = buf.replace(iac_cmd, b'', 1)
-1
View File
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 GNS3 Technologies Inc.
#
-1
View File
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 GNS3 Technologies Inc.
#
+4 -5
View File
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 GNS3 Technologies Inc.
#
@@ -83,7 +82,7 @@ def list_images(type):
"md5sum": md5sum(os.path.join(root, filename)),
"filesize": os.stat(os.path.join(root, filename)).st_size})
except OSError as e:
log.warning("Can't add image {}: {}".format(path, str(e)))
log.warning(f"Can't add image {path}: {str(e)}")
return images
@@ -170,7 +169,7 @@ def md5sum(path, stopped_event=None):
with open(path, 'rb') as f:
while True:
if stopped_event is not None and stopped_event.is_set():
log.error("MD5 sum calculation of `{}` has stopped due to cancellation".format(path))
log.error(f"MD5 sum calculation of `{path}` has stopped due to cancellation")
return
buf = f.read(128)
if not buf:
@@ -182,7 +181,7 @@ def md5sum(path, stopped_event=None):
return None
try:
with open('{}.md5sum'.format(path), 'w+') as f:
with open(f'{path}.md5sum', 'w+') as f:
f.write(digest)
except OSError as e:
log.error("Can't write digest of %s: %s", path, str(e))
@@ -195,6 +194,6 @@ def remove_checksum(path):
Remove the checksum of an image from cache if exists
"""
path = '{}.md5sum'.format(path)
path = f'{path}.md5sum'
if os.path.exists(path):
os.remove(path)
+6 -7
View File
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 GNS3 Technologies Inc.
#
@@ -46,10 +45,10 @@ def _get_windows_interfaces_from_registry():
hkeycard = winreg.OpenKey(hkey, network_card_id)
guid, _ = winreg.QueryValueEx(hkeycard, "ServiceName")
netcard, _ = winreg.QueryValueEx(hkeycard, "Description")
connection = r"SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}" + "\{}\Connection".format(guid)
connection = r"SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}" + fr"\{guid}\Connection"
hkeycon = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, connection)
name, _ = winreg.QueryValueEx(hkeycon, "Name")
interface = r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{}".format(guid)
interface = fr"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{guid}"
hkeyinterface = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, interface)
is_dhcp_enabled, _ = winreg.QueryValueEx(hkeyinterface, "EnableDHCP")
if is_dhcp_enabled:
@@ -74,7 +73,7 @@ def _get_windows_interfaces_from_registry():
winreg.CloseKey(hkeycard)
winreg.CloseKey(hkey)
except OSError as e:
log.error("could not read registry information: {}".format(e))
log.error(f"could not read registry information: {e}")
return interfaces
@@ -92,7 +91,7 @@ def get_windows_interfaces():
interfaces = []
try:
locator = win32com.client.Dispatch("WbemScripting.SWbemLocator")
service = locator.ConnectServer(".", "root\cimv2")
service = locator.ConnectServer(".", r"root\cimv2")
network_configs = service.InstancesOf("Win32_NetworkAdapterConfiguration")
# more info on Win32_NetworkAdapter: http://msdn.microsoft.com/en-us/library/aa394216%28v=vs.85%29.aspx
for adapter in service.InstancesOf("Win32_NetworkAdapter"):
@@ -188,7 +187,7 @@ def interfaces():
net_if_addrs = psutil.net_if_addrs()
for interface in sorted(net_if_addrs.keys()):
if allowed_interfaces and interface not in allowed_interfaces and not interface.startswith("gns3tap"):
log.warning("Interface '{}' is not allowed to be used on this server".format(interface))
log.warning(f"Interface '{interface}' is not allowed to be used on this server")
continue
ip_address = ""
mac_address = ""
@@ -221,7 +220,7 @@ def interfaces():
message = "pywin32 module is not installed, please install it on the server to get the available interface names"
raise ComputeError(message)
except Exception as e:
log.error("uncaught exception {type}".format(type=type(e)), exc_info=1)
log.error(f"uncaught exception {type(e)}", exc_info=1)
raise ComputeError(f"uncaught exception: {e}")
if service_installed is False:
+1 -1
View File
@@ -64,7 +64,7 @@ class NotificationQueue(asyncio.Queue):
msg["memory_usage_percent"] = psutil.virtual_memory().percent
msg["disk_usage_percent"] = psutil.disk_usage(get_default_project_directory()).percent
except OSError as e:
log.warning("Could not get CPU and memory usage from psutil: {}".format(e))
log.warning(f"Could not get CPU and memory usage from psutil: {e}")
return msg
async def get_json(self, timeout):
+1 -1
View File
@@ -121,7 +121,7 @@ def get_size(data, default_width=0, default_height=0):
else:
height = _svg_convert_size(height_attr)
except (AttributeError, IndexError) as e:
raise ValueError("Invalid SVG file: {}".format(e))
raise ValueError(f"Invalid SVG file: {e}")
return width, height, filetype
+3 -3
View File
@@ -27,7 +27,7 @@ def qt_font_to_style(font, color):
if font is None:
font = "TypeWriter,10,-1,5,75,0,0,0,0,0"
font_info = font.split(",")
style = "font-family: {};font-size: {};".format(font_info[0], font_info[1])
style = f"font-family: {font_info[0]};font-size: {font_info[1]};"
if font_info[4] == "75":
style += "font-weight: bold;"
if font_info[5] == "1":
@@ -37,8 +37,8 @@ def qt_font_to_style(font, color):
color = "000000"
if len(color) == 9:
style += "fill: #" + color[-6:] + ";"
style += "fill-opacity: {};".format(round(1.0 / 255 * int(color[:3][-2:], base=16), 2))
style += f"fill-opacity: {round(1.0 / 255 * int(color[:3][-2:], base=16), 2)};"
else:
style += "fill: #" + color[-6:] + ";"
style += "fill-opacity: {};".format(1.0)
style += f"fill-opacity: {1.0};"
return style
+19 -20
View File
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 GNS3 Technologies Inc.
#
@@ -44,7 +43,7 @@ def parse_networking_file():
pairs = dict()
allocated_subnets = []
try:
with open(VMWARE_NETWORKING_FILE, "r", encoding="utf-8") as f:
with open(VMWARE_NETWORKING_FILE, encoding="utf-8") as f:
version = f.readline()
for line in f.read().splitlines():
try:
@@ -55,9 +54,9 @@ def parse_networking_file():
if key.endswith("HOSTONLY_SUBNET"):
allocated_subnets.append(value)
except ValueError:
raise SystemExit("Error while parsing {}".format(VMWARE_NETWORKING_FILE))
raise SystemExit(f"Error while parsing {VMWARE_NETWORKING_FILE}")
except OSError as e:
raise SystemExit("Cannot open {}: {}".format(VMWARE_NETWORKING_FILE, e))
raise SystemExit(f"Cannot open {VMWARE_NETWORKING_FILE}: {e}")
return version, pairs, allocated_subnets
@@ -71,9 +70,9 @@ def write_networking_file(version, pairs):
with open(VMWARE_NETWORKING_FILE, "w", encoding="utf-8") as f:
f.write(version)
for key, value in vmnets.items():
f.write("answer {} {}\n".format(key, value))
f.write(f"answer {key} {value}\n")
except OSError as e:
raise SystemExit("Cannot open {}: {}".format(VMWARE_NETWORKING_FILE, e))
raise SystemExit(f"Cannot open {VMWARE_NETWORKING_FILE}: {e}")
# restart VMware networking service
if sys.platform.startswith("darwin"):
@@ -98,7 +97,7 @@ def parse_vmnet_range(start, end):
if len(values) != 2:
raise argparse.ArgumentTypeError("vmnet range must consist of 2 numbers")
if not start <= values[0] or not values[1] <= end:
raise argparse.ArgumentTypeError("vmnet range must be between {} and {}".format(start, end))
raise argparse.ArgumentTypeError(f"vmnet range must be between {start} and {end}")
setattr(args, self.dest, values)
return Range
@@ -176,14 +175,14 @@ def vmnet_windows(args, vmnet_range_start, vmnet_range_end):
for vmnet_number in range(1, 20):
if vmnet_number in (1, 8):
continue
print("Removing vmnet{}...".format(vmnet_number))
os.system('"{}" -- remove adapter vmnet{}'.format(vnetlib_path, vmnet_number))
print(f"Removing vmnet{vmnet_number}...")
os.system(f'"{vnetlib_path}" -- remove adapter vmnet{vmnet_number}')
else:
for vmnet_number in range(vmnet_range_start, vmnet_range_end + 1):
if vmnet_number in (1, 8):
continue
print("Adding vmnet{}...".format(vmnet_number))
os.system('"{}" -- add adapter vmnet{}'.format(vnetlib_path, vmnet_number))
print(f"Adding vmnet{vmnet_number}...")
os.system(f'"{vnetlib_path}" -- add adapter vmnet{vmnet_number}')
os.system("net stop npf")
os.system("net start npf")
os.system("net stop npcap")
@@ -203,9 +202,9 @@ def vmnet_unix(args, vmnet_range_start, vmnet_range_end):
version, pairs, allocated_subnets = parse_networking_file()
if args.list and not sys.platform.startswith("win"):
for vmnet_number in range(1, 256):
vmnet_name = "VNET_{}_VIRTUAL_ADAPTER".format(vmnet_number)
vmnet_name = f"VNET_{vmnet_number}_VIRTUAL_ADAPTER"
if vmnet_name in pairs:
print("vmnet{}".format(vmnet_number))
print(f"vmnet{vmnet_number}")
return
if args.clean:
@@ -216,7 +215,7 @@ def vmnet_unix(args, vmnet_range_start, vmnet_range_end):
del pairs[key]
else:
for vmnet_number in range(vmnet_range_start, vmnet_range_end + 1):
vmnet_name = "VNET_{}_VIRTUAL_ADAPTER".format(vmnet_number)
vmnet_name = f"VNET_{vmnet_number}_VIRTUAL_ADAPTER"
if vmnet_name in pairs:
continue
allocated_subnet = None
@@ -228,13 +227,13 @@ def vmnet_unix(args, vmnet_range_start, vmnet_range_end):
break
if allocated_subnet is None:
print("Couldn't allocate a subnet for vmnet{}".format(vmnet_number))
print(f"Couldn't allocate a subnet for vmnet{vmnet_number}")
continue
print("Adding vmnet{}...".format(vmnet_number))
pairs["VNET_{}_HOSTONLY_NETMASK".format(vmnet_number)] = "255.255.255.0"
pairs["VNET_{}_HOSTONLY_SUBNET".format(vmnet_number)] = allocated_subnet
pairs["VNET_{}_VIRTUAL_ADAPTER".format(vmnet_number)] = "yes"
print(f"Adding vmnet{vmnet_number}...")
pairs[f"VNET_{vmnet_number}_HOSTONLY_NETMASK"] = "255.255.255.0"
pairs[f"VNET_{vmnet_number}_HOSTONLY_SUBNET"] = allocated_subnet
pairs[f"VNET_{vmnet_number}_VIRTUAL_ADAPTER"] = "yes"
write_networking_file(version, pairs)
@@ -246,7 +245,7 @@ def main():
parser = argparse.ArgumentParser(description='%(prog)s add/remove vmnet interfaces')
parser.add_argument('-r', "--range", nargs='+', action=parse_vmnet_range(1, 255),
type=int, help="vmnet range to add (default is {} {})".format(DEFAULT_RANGE[0], DEFAULT_RANGE[1]))
type=int, help=f"vmnet range to add (default is {DEFAULT_RANGE[0]} {DEFAULT_RANGE[1]})")
parser.add_argument("-C", "--clean", action="store_true", help="remove all vmnets excepting vmnet1 and vmnet8")
parser.add_argument("-l", "--list", action="store_true", help="list all existing vmnets (UNIX only)")
+9 -10
View File
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 GNS3 Technologies Inc.
#
@@ -37,11 +36,11 @@ def parse_add_loopback():
def __call__(self, parser, args, values, option_string=None):
try:
ipaddress.IPv4Interface("{}/{}".format(values[1], values[2]))
ipaddress.IPv4Interface(f"{values[1]}/{values[2]}")
except ipaddress.AddressValueError as e:
raise argparse.ArgumentTypeError("Invalid IP address: {}".format(e))
raise argparse.ArgumentTypeError(f"Invalid IP address: {e}")
except ipaddress.NetmaskValueError as e:
raise argparse.ArgumentTypeError("Invalid subnet mask: {}".format(e))
raise argparse.ArgumentTypeError(f"Invalid subnet mask: {e}")
setattr(args, self.dest, values)
return Add
@@ -52,7 +51,7 @@ def add_loopback(devcon_path, name, ip_address, netmask):
previous_adapters = wmi.WMI().Win32_NetworkAdapter()
for adapter in previous_adapters:
if "Loopback" in adapter.Description and adapter.NetConnectionID == name:
raise SystemExit('Windows loopback adapter named "{}" already exists'.format(name))
raise SystemExit(f'Windows loopback adapter named "{name}" already exists')
# install a new Windows loopback adapter
os.system('"{}" install {}\\inf\\netloop.inf *MSLOOP'.format(devcon_path, os.path.expandvars("%WINDIR%")))
@@ -60,11 +59,11 @@ def add_loopback(devcon_path, name, ip_address, netmask):
# configure the new Windows loopback adapter
for adapter in wmi.WMI().Win32_NetworkAdapter():
if "Loopback" in adapter.Description and adapter not in previous_adapters:
print('Renaming loopback adapter "{}" to "{}"'.format(adapter.NetConnectionID, name))
print(f'Renaming loopback adapter "{adapter.NetConnectionID}" to "{name}"')
adapter.NetConnectionID = name
for network_config in wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True):
if network_config.InterfaceIndex == adapter.InterfaceIndex:
print('Configuring loopback adapter "{}" with {} {}'.format(name, ip_address, netmask))
print(f'Configuring loopback adapter "{name}" with {ip_address} {netmask}')
retcode = network_config.EnableStatic(IPAddress=[ip_address], SubnetMask=[netmask])[0]
if retcode == 1:
print("A reboot is required")
@@ -88,12 +87,12 @@ def remove_loopback(devcon_path, name):
for adapter in wmi.WMI().Win32_NetworkAdapter():
if "Loopback" in adapter.Description and adapter.NetConnectionID == name:
# remove a Windows loopback adapter
print('Removing loopback adapter "{}"'.format(name))
os.system('"{}" remove @{}'.format(devcon_path, adapter.PNPDeviceID))
print(f'Removing loopback adapter "{name}"')
os.system(f'"{devcon_path}" remove @{adapter.PNPDeviceID}')
deleted = True
if not deleted:
raise SystemExit('Could not find adapter "{}"'.format(name))
raise SystemExit(f'Could not find adapter "{name}"')
# update winpcap/npcap services
os.system("net stop npf")