Skip to content

Commit

Permalink
Automatically upgrade strings to f-string
Browse files Browse the repository at this point in the history
Used flynt to convert strings to f-strings, where safely possible.

Usage:
flynt .

Related #2372
  • Loading branch information
MattHag authored and pfps committed Mar 13, 2024
1 parent 97ddee1 commit e92f1a8
Show file tree
Hide file tree
Showing 26 changed files with 155 additions and 155 deletions.
4 changes: 2 additions & 2 deletions lib/hidapi/hidconsole.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def matchfn(bid, vid, pid, _a, _b):
print(".. Opening device", device)
handle = _hid.open_path(device)
if not handle:
sys.exit("!! Failed to open %s, aborting." % device)
sys.exit(f"!! Failed to open {device}, aborting.")
print(
".. Opened handle %r, vendor %r product %r serial %r."
% (handle, _hid.get_manufacturer(handle), _hid.get_product(handle), _hid.get_serial(handle))
Expand Down Expand Up @@ -243,7 +243,7 @@ def main():
time.sleep(1)

finally:
print(".. Closing handle %r" % handle)
print(f".. Closing handle {handle!r}")
_hid.close(handle)
if interactive:
readline.write_history_file(args.history)
Expand Down
2 changes: 1 addition & 1 deletion lib/logitech_receiver/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ def check_message(data):
if report_lengths.get(report_id) == len(data):
return True
else:
logger.warning("unexpected message size: report_id %02X message %s" % (report_id, _strhex(data)))
logger.warning(f"unexpected message size: report_id {report_id:02X} message {_strhex(data)}")
return False


Expand Down
4 changes: 2 additions & 2 deletions lib/logitech_receiver/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ def flag_names(self, value):
yield str(self._indexed[k])

if unknown_bits:
yield "unknown:%06X" % unknown_bits
yield f"unknown:{unknown_bits:06X}"

def _sort_values(self):
self._values = sorted(self._values)
Expand Down Expand Up @@ -501,7 +501,7 @@ def __len__(self):
return len(self._values)

def __repr__(self):
return "NamedInts(%s)" % ", ".join(repr(v) for v in self._values)
return f"NamedInts({', '.join(repr(v) for v in self._values)})"

def __or__(self, other):
return NamedInts(**self.__dict__, **other.__dict__)
Expand Down
16 changes: 8 additions & 8 deletions lib/logitech_receiver/descriptors.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,18 +85,18 @@ def _D(
if "Trackball" in name
else None
)
assert kind is not None, "descriptor for %s does not have kind set" % name
assert kind is not None, f"descriptor for {name} does not have kind set"

if protocol is not None:
if wpid:
for w in wpid if isinstance(wpid, tuple) else (wpid,):
if protocol > 1.0:
assert w[0:1] == "4", "%s has protocol %0.1f, wpid %s" % (name, protocol, w)
assert w[0:1] == "4", f"{name} has protocol {protocol:0.1f}, wpid {w}"
else:
if w[0:1] == "1":
assert kind == _DK.mouse, "%s has protocol %0.1f, wpid %s" % (name, protocol, w)
assert kind == _DK.mouse, f"{name} has protocol {protocol:0.1f}, wpid {w}"
elif w[0:1] == "2":
assert kind in (_DK.keyboard, _DK.numpad), "%s has protocol %0.1f, wpid %s" % (name, protocol, w)
assert kind in (_DK.keyboard, _DK.numpad), f"{name} has protocol {protocol:0.1f}, wpid {w}"

device_descriptor = _DeviceDescriptor(
name=name,
Expand All @@ -112,18 +112,18 @@ def _D(

if usbid:
found = get_usbid(usbid)
assert found is None, "duplicate usbid in device descriptors: %s" % (found,)
assert found is None, f"duplicate usbid in device descriptors: {found}"
if btid:
found = get_btid(btid)
assert found is None, "duplicate btid in device descriptors: %s" % (found,)
assert found is None, f"duplicate btid in device descriptors: {found}"

assert codename not in DEVICES, "duplicate codename in device descriptors: %s" % (DEVICES[codename],)
assert codename not in DEVICES, f"duplicate codename in device descriptors: {DEVICES[codename]}"
if codename:
DEVICES[codename] = device_descriptor

if wpid:
for w in wpid if isinstance(wpid, tuple) else (wpid,):
assert w not in DEVICES_WPID, "duplicate wpid in device descriptors: %s" % (DEVICES_WPID[w],)
assert w not in DEVICES_WPID, f"duplicate wpid in device descriptors: {DEVICES_WPID[w]}"
DEVICES_WPID[w] = device_descriptor


Expand Down
20 changes: 10 additions & 10 deletions lib/logitech_receiver/diversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,7 +493,7 @@ def __init__(self, args, source=None, warn=True):

def __str__(self):
source = "(" + self.source + ")" if self.source else ""
return "Rule%s[%s]" % (source, ", ".join([c.__str__() for c in self.components]))
return f"Rule{source}[{', '.join([c.__str__() for c in self.components])}]"

def evaluate(self, feature, notification, device, last_result):
if logger.isEnabledFor(logging.DEBUG):
Expand Down Expand Up @@ -832,16 +832,16 @@ def __init__(self, args, warn=True):

if not args or not isinstance(args, (list, str)):
if warn:
logger.warning("rule Key arguments unknown: %s" % args)
logger.warning(f"rule Key arguments unknown: {args}")
key = default_key
action = default_action
elif isinstance(args, str):
logger.debug('rule Key assuming action "%s" for "%s"' % (default_action, args))
logger.debug(f'rule Key assuming action "{default_action}" for "{args}"')
key = args
action = default_action
elif isinstance(args, list):
if len(args) == 1:
logger.debug('rule Key assuming action "%s" for "%s"' % (default_action, args))
logger.debug(f'rule Key assuming action "{default_action}" for "{args}"')
key, action = args[0], default_action
elif len(args) >= 2:
key, action = args[:2]
Expand All @@ -850,18 +850,18 @@ def __init__(self, args, warn=True):
self.key = _CONTROL[key]
else:
if warn:
logger.warning("rule Key key name not name of a Logitech key: %s" % key)
logger.warning(f"rule Key key name not name of a Logitech key: {key}")
self.key = default_key

if isinstance(action, str) and action in (self.DOWN, self.UP):
self.action = action
else:
if warn:
logger.warning("rule Key action unknown: %s, assuming %s" % (action, default_action))
logger.warning(f"rule Key action unknown: {action}, assuming {default_action}")
self.action = default_action

def __str__(self):
return "Key: %s (%s)" % ((str(self.key) if self.key else "None"), self.action)
return f"Key: {str(self.key) if self.key else 'None'} ({self.action})"

def evaluate(self, feature, notification, device, last_result):
if logger.isEnabledFor(logging.DEBUG):
Expand All @@ -880,7 +880,7 @@ def __init__(self, args, warn=True):

if not args or not isinstance(args, str):
if warn:
logger.warning("rule KeyDown arguments unknown: %s" % args)
logger.warning(f"rule KeyDown arguments unknown: {args}")
key = default_key
elif isinstance(args, str):
key = args
Expand All @@ -889,11 +889,11 @@ def __init__(self, args, warn=True):
self.key = _CONTROL[key]
else:
if warn:
logger.warning("rule Key key name not name of a Logitech key: %s" % key)
logger.warning(f"rule Key key name not name of a Logitech key: {key}")
self.key = default_key

def __str__(self):
return "KeyIsDown: %s" % (str(self.key) if self.key else "None")
return f"KeyIsDown: {str(self.key) if self.key else 'None'}"

def evaluate(self, feature, notification, device, last_result):
if logger.isEnabledFor(logging.DEBUG):
Expand Down
10 changes: 5 additions & 5 deletions lib/logitech_receiver/hidpp10.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@


def read_register(device, register_number, *params):
assert device is not None, "tried to read register %02X from invalid device %s" % (register_number, device)
assert device is not None, f"tried to read register {register_number:02X} from invalid device {device}"
# support long registers by adding a 2 in front of the register number
request_id = 0x8100 | (int(register_number) & 0x2FF)
return device.request(request_id, *params)


def write_register(device, register_number, *value):
assert device is not None, "tried to write register %02X to invalid device %s" % (register_number, device)
assert device is not None, f"tried to write register {register_number:02X} to invalid device {device}"
# support long registers by adding a 2 in front of the register number
request_id = 0x8000 | (int(register_number) & 0x2FF)
return device.request(request_id, *value)
Expand Down Expand Up @@ -87,7 +87,7 @@ def get_firmware(self, device):
return

fw_version = _strhex(reply[1:3])
fw_version = "%s.%s" % (fw_version[0:2], fw_version[2:4])
fw_version = f"{fw_version[0:2]}.{fw_version[2:4]}"
reply = read_register(device, REGISTERS.firmware, 0x02)
if reply:
fw_version += ".B" + _strhex(reply[1:3])
Expand All @@ -97,14 +97,14 @@ def get_firmware(self, device):
reply = read_register(device, REGISTERS.firmware, 0x04)
if reply:
bl_version = _strhex(reply[1:3])
bl_version = "%s.%s" % (bl_version[0:2], bl_version[2:4])
bl_version = f"{bl_version[0:2]}.{bl_version[2:4]}"
bl = _FirmwareInfo(FIRMWARE_KIND.Bootloader, "", bl_version, None)
firmware[1] = bl

reply = read_register(device, REGISTERS.firmware, 0x03)
if reply:
o_version = _strhex(reply[1:3])
o_version = "%s.%s" % (o_version[0:2], o_version[2:4])
o_version = f"{o_version[0:2]}.{o_version[2:4]}"
o = _FirmwareInfo(FIRMWARE_KIND.Other, "", o_version, None)
firmware[2] = o

Expand Down
12 changes: 6 additions & 6 deletions lib/logitech_receiver/hidpp20.py
Original file line number Diff line number Diff line change
Expand Up @@ -577,7 +577,7 @@ def _query_key(self, index: int):
RatioZone=3, # 4 bytes, left, bottom, width, height; unit 1/240 pad size
ScaleFactor=4, # 2-byte integer, with 256 as normal scale
)
PARAM._fallback = lambda x: "unknown:%04X" % x
PARAM._fallback = lambda x: f"unknown:{x:04X}"


class SubParam:
Expand Down Expand Up @@ -627,7 +627,7 @@ def __repr__(self):
finger_force=9,
zone=10,
)
SPEC._fallback = lambda x: "unknown:%04X" % x
SPEC._fallback = lambda x: f"unknown:{x:04X}"

# Action Ids for feature GESTURE_2
ACTION_ID = _NamedInts(
Expand All @@ -644,7 +644,7 @@ def __repr__(self):
ScrollHorizontalOnly=11,
ScrollVerticalOnly=12,
)
ACTION_ID._fallback = lambda x: "unknown:%04X" % x
ACTION_ID._fallback = lambda x: f"unknown:{x:04X}"


class Gesture:
Expand Down Expand Up @@ -1396,9 +1396,9 @@ def get_firmware(self, device):
level = ord(fw_info[:1]) & 0x0F
if level == 0 or level == 1:
name, version_major, version_minor, build = _unpack("!3sBBH", fw_info[1:8])
version = "%02X.%02X" % (version_major, version_minor)
version = f"{version_major:02X}.{version_minor:02X}"
if build:
version += ".B%04X" % build
version += f".B{build:04X}"
extras = fw_info[9:].rstrip(b"\x00") or None
fw_info = _FirmwareInfo(FIRMWARE_KIND[level], name.decode("ascii"), version, extras)
elif level == FIRMWARE_KIND.Hardware:
Expand Down Expand Up @@ -1716,7 +1716,7 @@ def get_remaining_pairing(self, device):
result = feature_request(device, FEATURE.REMAINING_PAIRING, 0x0)
if result:
result = _unpack("!B", result[:1])[0]
FEATURE._fallback = lambda x: "unknown:%04X" % x
FEATURE._fallback = lambda x: f"unknown:{x:04X}"
return result

def config_change(self, device, configuration, no_reply=False):
Expand Down
6 changes: 3 additions & 3 deletions lib/logitech_receiver/hidpp20_constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@
# Fake features for Solaar internal use
MOUSE_GESTURE=0xFE00,
)
FEATURE._fallback = lambda x: "unknown:%04X" % x
FEATURE._fallback = lambda x: f"unknown:{x:04X}"

FEATURE_FLAG = NamedInts(internal=0x20, hidden=0x40, obsolete=0x80)

Expand Down Expand Up @@ -238,7 +238,7 @@
Finger10=99,
DeviceSpecificRawData=100,
)
GESTURE._fallback = lambda x: "unknown:%04X" % x
GESTURE._fallback = lambda x: f"unknown:{x:04X}"

# Param Ids for feature GESTURE_2
PARAM = NamedInts(
Expand All @@ -247,4 +247,4 @@
RatioZone=3, # 4 bytes, left, bottom, width, height; unit 1/240 pad size
ScaleFactor=4, # 2-byte integer, with 256 as normal scale
)
PARAM._fallback = lambda x: "unknown:%04X" % x
PARAM._fallback = lambda x: f"unknown:{x:04X}"
2 changes: 1 addition & 1 deletion lib/logitech_receiver/listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def __str__(self):
return str(int(self))

def __repr__(self):
return "<_ThreadedHandle(%s)>" % self.path
return f"<_ThreadedHandle({self.path})>"

def __bool__(self):
return bool(self._local)
Expand Down
2 changes: 1 addition & 1 deletion lib/logitech_receiver/receiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ def _unpair_device(self, key, force=False):
logger.info("%s unpaired device %s", self, dev)
else:
logger.error("%s failed to unpair device %s", self, dev)
raise Exception("failed to unpair device %s: %s" % (dev.name, key))
raise Exception(f"failed to unpair device {dev.name}: {key}")

def _unpair_device_per_receiver(self, key):
"""Receiver specific unpairing."""
Expand Down
24 changes: 12 additions & 12 deletions lib/logitech_receiver/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ def __str__(self):
self.name,
self._value,
)
return "<Setting([%s:%s] %s)>" % (self._rw.kind, self._validator.kind if self._validator else None, self.name)
return f"<Setting([{self._rw.kind}:{self._validator.kind if self._validator else None}] {self.name})>"

__repr__ = __str__

Expand Down Expand Up @@ -747,7 +747,7 @@ def __init__(
assert fv & mv == fv
self.needs_current_value = any(m != 0xFF for m in mask)
else:
raise Exception("invalid mask '%r', type %s" % (mask, type(mask)))
raise Exception(f"invalid mask '{mask!r}', type {type(mask)}")

self.true_value = true_value
self.false_value = false_value
Expand Down Expand Up @@ -795,7 +795,7 @@ def prepare_write(self, new_value, current_value=None):
if new_value is None:
new_value = False
else:
assert isinstance(new_value, bool), "New value %s for boolean setting is not a boolean" % new_value
assert isinstance(new_value, bool), f"New value {new_value} for boolean setting is not a boolean"

to_write = self.true_value if new_value else self.false_value

Expand Down Expand Up @@ -1033,7 +1033,7 @@ def to_string(self, value):
def validate_read(self, reply_bytes):
reply_value = _bytes2int(reply_bytes[self._read_skip_byte_count : self._read_skip_byte_count + self._byte_count])
valid_value = self.choices[reply_value]
assert valid_value is not None, "%s: failed to validate read value %02X" % (self.__class__.__name__, reply_value)
assert valid_value is not None, f"{self.__class__.__name__}: failed to validate read value {reply_value:02X}"
return valid_value

def prepare_write(self, new_value, current_value=None):
Expand All @@ -1042,7 +1042,7 @@ def prepare_write(self, new_value, current_value=None):
else:
value = self.choice(new_value)
if value is None:
raise ValueError("invalid choice %r" % new_value)
raise ValueError(f"invalid choice {new_value!r}")
assert isinstance(value, _NamedInt)
return self._write_prefix_bytes + value.bytes(self._byte_count)

Expand Down Expand Up @@ -1191,13 +1191,13 @@ def __init__(self, min_value=0, max_value=255, byte_count=1):

def validate_read(self, reply_bytes):
reply_value = _bytes2int(reply_bytes[: self._byte_count])
assert reply_value >= self.min_value, "%s: failed to validate read value %02X" % (self.__class__.__name__, reply_value)
assert reply_value <= self.max_value, "%s: failed to validate read value %02X" % (self.__class__.__name__, reply_value)
assert reply_value >= self.min_value, f"{self.__class__.__name__}: failed to validate read value {reply_value:02X}"
assert reply_value <= self.max_value, f"{self.__class__.__name__}: failed to validate read value {reply_value:02X}"
return reply_value

def prepare_write(self, new_value, current_value=None):
if new_value < self.min_value or new_value > self.max_value:
raise ValueError("invalid choice %r" % new_value)
raise ValueError(f"invalid choice {new_value!r}")
current_value = self.validate_read(current_value) if current_value is not None else None
to_write = _int2bytes(new_value, self._byte_count)
# current value is known and same as value to be written return None to signal not to write it
Expand Down Expand Up @@ -1276,16 +1276,16 @@ def validate_read(self, reply_bytes):
for n in range(self.count)
}
for n in range(self.count):
assert rvs[n] >= self.min_value, "%s: failed to validate read value %02X" % (self.__class__.__name__, rvs[n])
assert rvs[n] <= self.max_value, "%s: failed to validate read value %02X" % (self.__class__.__name__, rvs[n])
assert rvs[n] >= self.min_value, f"{self.__class__.__name__}: failed to validate read value {rvs[n]:02X}"
assert rvs[n] <= self.max_value, f"{self.__class__.__name__}: failed to validate read value {rvs[n]:02X}"
return rvs

def prepare_write(self, new_values):
if len(new_values) != self.count:
raise ValueError("wrong number of values %r" % new_values)
raise ValueError(f"wrong number of values {new_values!r}")
for new_value in new_values:
if new_value < self.min_value or new_value > self.max_value:
raise ValueError("invalid value %r" % new_value)
raise ValueError(f"invalid value {new_value!r}")
bytes = self.write_prefix_bytes + b"".join(_int2bytes(new_values[n], self.bc, signed=True) for n in range(self.count))
return bytes

Expand Down
Loading

0 comments on commit e92f1a8

Please sign in to comment.