Skip to content

Commit

Permalink
chore: convert old strings to f-strings
Browse files Browse the repository at this point in the history
Closes: #382
Signed-off-by: Cedric Hombourger <[email protected]>
  • Loading branch information
chombourger committed Jan 21, 2024
1 parent 8bb884f commit 3195f4e
Show file tree
Hide file tree
Showing 38 changed files with 394 additions and 427 deletions.
31 changes: 15 additions & 16 deletions mtda-cli
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ class Application:
if isinstance(result, str):
print(result)
else:
print("Device command '{0}' failed!".format(
" ".join(args)), file=sys.stderr)
print(f"Device command '{' '.join(args)}' failed!",
file=sys.stderr)

def console_clear(self, args):
self.client().console_clear()
Expand Down Expand Up @@ -139,7 +139,7 @@ class Application:
new_status = server.target_status()
if previous_status != new_status:
server.console_print(
"\r\n*** Target is now %s ***\r\n" % (new_status))
f"\r\n*** Target is now {new_status} ***\r\n")
elif c == 'q':
self.screen.capture_stop()
self.exiting = True
Expand All @@ -153,8 +153,7 @@ class Application:
new_status, writing, written = server.storage_status()
if new_status != previous_status:
server.console_print(
"\r\n*** Storage now connected to "
"%s ***\r\n" % (new_status))
f"\r\n*** Storage now connected to {new_status} ***\r\n")
elif c == 't':
server.toggle_timestamps()
elif c == 'u':
Expand All @@ -179,7 +178,7 @@ class Application:
r = requests.post(url=endpoint, data=data)
server = self.client()
server.console_print(
"\r\n*** console buffer posted to %s ***\r\n" % (r.text))
f"\r\n*** console buffer posted to {r.text} ***\r\n")

def console_prompt(self, args):
data = self.client().console_prompt(args.prompt)
Expand Down Expand Up @@ -320,11 +319,11 @@ class Application:

def _human_readable_size(self, size):
if size < 1024*1024:
return "{:d} KiB".format(int(size/1024))
return f"{int(size / 1024):d} KiB"
elif size < 1024*1024*1024:
return "{:d} MiB".format(int(size/1024/1024))
return f"{int(size / 1024 / 1024):d} MiB"
else:
return "{:.2f} GiB".format(size/1024/1024/1024)
return f"{size / 1024 / 1024 / 1024:.2f} GiB"

def _storage_write_cb(self, imgname, totalread,
inputsize, totalwritten, imagesize):
Expand Down Expand Up @@ -370,7 +369,7 @@ class Application:
sys.stdout.flush()
except Exception as e:
msg = e.msg if hasattr(e, 'msg') else str(e)
print("\n'storage write' failed! ({})".format(msg),
print(f"\n'storage write' failed! ({msg})",
file=sys.stderr)
result = 1
return result
Expand Down Expand Up @@ -410,7 +409,7 @@ class Application:
tgt_status = client.target_status()
uptime = ""
if tgt_status == "ON":
uptime = " (up %s)" % self.target_uptime()
uptime = f" (up {self.target_uptime()})"
try:
remote_version = client.agent_version()
except (zerorpc.RemoteError) as e:
Expand All @@ -427,11 +426,11 @@ class Application:
socket.gethostname(), host.version, ""))
print("Remote : %s (%s)%30s\r" % (
remote, remote_version, ""))
print("Prefix key: : ctrl-%s\r" % (prefix_key))
print("Session : %s\r" % (session))
print(f"Prefix key: : ctrl-{prefix_key}\r")
print(f"Session : {session}\r")
print("Target : %-6s%s%s\r" % (tgt_status, locked, uptime))
print("Storage on : %-6s%s\r" % (storage_status, locked))
print("Storage writes : %s (%s)\r" % (written, writing))
print(f"Storage writes : {written} ({writing})\r")

# Print status of the USB ports
ports = client.usb_ports()
Expand All @@ -442,7 +441,7 @@ class Application:
# Print video stream details
url = client.video_url()
if url is not None:
print("Video stream : %s\r" % (url))
print(f"Video stream : {url}\r")

def target_off(self, args=None):
status = self.client().target_off()
Expand Down Expand Up @@ -506,7 +505,7 @@ class Application:

def print_version(self):
agent = MultiTenantDeviceAccess()
print("MTDA version: %s" % agent.version)
print(f"MTDA version: {agent.version}")

def main(self):
parser = ArgumentParser(
Expand Down
20 changes: 9 additions & 11 deletions mtda-config
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class Config:
def __save_as_config(self, config):
with open("./.config", "w") as config_file:
for key in config:
config_file.write("{}={}\n".format(key, config[key]))
config_file.write(f"{key}={config[key]}\n")

def __save_as_ini(self, config, output_file=None):
if not output_file:
Expand All @@ -54,15 +54,14 @@ class Config:
config_name = template.group(2).lower()
# Write the module_name
if module_name != current_module:
config_file.write("\n[{}]\n".format(module_name))
config_file.write(f"\n[{module_name}]\n")
current_module = module_name
config_file.write(" {} = {}\n"
.format(config_name, config[key]))
config_file.write(f" {config_name} = {config[key]}\n")

def save_config(self, nodes=[], output_file=None):
config_entries = {}
for node in nodes:
config = "CONFIG_{}".format(node.item.name)
config = f"CONFIG_{node.item.name}"
config_entries[config] = node.item.str_value
logging.debug("save_config: %s=%s", config, config_entries[config])

Expand All @@ -86,8 +85,7 @@ class Config:
if module_name not in skip_list:
# Handle invalid cases later
(config, value) = line.split("=")
config = "CONFIG_{}_{}".format(module_name,
config.strip()).upper()
config = f"CONFIG_{module_name}_{config.strip()}".upper()
config_entries[config] = value.strip()
return config_entries

Expand Down Expand Up @@ -353,7 +351,7 @@ class ConfigApp:
"Q/q - quit | Esc - previous screen | Arrow keys - navigation"
)
footer_right_text = urwid.Text(
"Kconfig: {}".format(self.kconfig_file), align="right"
f"Kconfig: {self.kconfig_file}", align="right"
)
footer_column = urwid.Columns([footer_left_text, footer_right_text])
footer_column = urwid.AttrMap(footer_column, "footer")
Expand All @@ -377,7 +375,7 @@ def start_config():
"-v",
"--version",
action="version",
version="mtda config generator {}".format(mtda.__version__),
version=f"mtda config generator {mtda.__version__}",
)
parser.add_argument(
"-d",
Expand Down Expand Up @@ -413,12 +411,12 @@ def start_config():

if args.config:
if not os.path.exists(args.config):
print("Cannot access config file [ {} ]\n".format(args.config))
print(f"Cannot access config file [ {args.config} ]\n")
parser.print_help()
sys.exit(1)

if not os.path.exists(kconfig_file):
print("Cannot access Kconfig file [ {} ]\n".format(kconfig_file))
print(f"Cannot access Kconfig file [ {kconfig_file} ]\n")
parser.print_help()
sys.exit(1)

Expand Down
6 changes: 3 additions & 3 deletions mtda-service
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,11 @@ class Application:
name = self.agent.name
info = zeroconf.ServiceInfo(
type_=deviceType,
name='{}.{}'.format(name, deviceType),
name=f'{name}.{deviceType}',
addresses=[socket.inet_aton(self._ip())],
port=int(self.agent.ctrlport),
properties=props,
server='{}.local.'.format(name))
server=f'{name}.local.')

try:
zc.register_service(info)
Expand All @@ -113,7 +113,7 @@ class Application:

def print_version(self):
agent = MultiTenantDeviceAccess()
print("MTDA version: %s" % agent.version)
print(f"MTDA version: {agent.version}")

def main(self):
config = None
Expand Down
3 changes: 1 addition & 2 deletions mtda-systemd-helper
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,7 @@ class Application:
sys.exit(0)

if config is not None and os.path.exists(config) is False:
print('could not find config file: '
'{}'.format(config), file=sys.stderr)
print(f'could not find config file: {config}', file=sys.stderr)
return 1

self.agent = MultiTenantDeviceAccess()
Expand Down
18 changes: 9 additions & 9 deletions mtda/assistant/homekit.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,13 @@ def get_relay(self, status=None):
return "1" if status == "ON" else 0

def relay_changed(self, status):
self.mtda.debug(3, "mtda.assistant.homekit.relay_changed(%s)" % status)
self.mtda.debug(3, f"mtda.assistant.homekit.relay_changed({status})")

result = self.get_relay(status)
self.relay_on.set_value(result)

self.mtda.debug(3, "mtda.assistant.homekit.relay_changed(): "
"%s" % str(result))
self.mtda.debug(3, "mtda.assistant.homekit."
f"relay_changed(): {str(result)}")
return result

def set_relay(self, state):
Expand All @@ -63,8 +63,8 @@ def set_relay(self, state):
self.mtda.target_off('homekit')
result = self.get_relay()

self.mtda.debug(3, "mtda.assistant.homekit.set_relay(): "
"%s" % str(result))
self.mtda.debug(3, "mtda.assistant.homekit."
f"set_relay(): {str(result)}")
return result

def get_relay_in_use(self, state):
Expand All @@ -76,8 +76,8 @@ def setup_message(self):
pincode = self.driver.state.pincode.decode()
result = self.mtda.env_set('homekit-setup-code', pincode, 'homekit')

self.mtda.debug(3, "mtda.assistant.homekit.setup_message(): "
"%s" % str(result))
self.mtda.debug(3, "mtda.assistant.homekit."
f"setup_message(): {str(result)}")
return result


Expand All @@ -103,8 +103,8 @@ def configure(self, conf):
dir = os.path.dirname(self.state)
os.makedirs(dir, mode=0o755, exist_ok=True)

self.mtda.debug(3, "mtda.assistant.homekit.configure(): "
"%s" % str(result))
self.mtda.debug(3, "mtda.assistant.homekit."
f"configure(): {str(result)}")
return result

def probe(self):
Expand Down
11 changes: 5 additions & 6 deletions mtda/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def __init__(self, host=None, session=None, config_files=None,
if name.endswith("'s"):
name = name.replace("'s", "")
elif USER is not None and HOST is not None:
name = "%s@%s" % (USER, HOST)
name = f"{USER}@{HOST}"
else:
name = "mtda"
self._session = os.getenv('MTDA_SESSION', name)
Expand Down Expand Up @@ -167,7 +167,7 @@ def storage_mount(self, part=None):
def storage_network(self, remote):
cmd = '/usr/sbin/nbd-client'
if os.path.exists(cmd) is False:
raise RuntimeError('{} not found'.format(cmd))
raise RuntimeError(f'{cmd} not found')

rdev = self._impl.storage_network()
if rdev is None:
Expand Down Expand Up @@ -256,7 +256,7 @@ def storage_write_image(self, path, callback=None):
import xml.etree.ElementTree as ET

bmap = ET.fromstring(bmap)
print("Discovered bmap file '{}'".format(bmap_path))
print(f"Discovered bmap file '{bmap_path}'")
bmapDict = self.parseBmap(bmap, bmap_path)
self._impl.storage_bmap_dict(bmapDict, self._session)
image_size = bmapDict['ImageSize']
Expand Down Expand Up @@ -311,8 +311,7 @@ def parseBmap(self, bmap, bmap_path):
"chksum": child.attrib["chksum"]
})
except Exception:
print("Error parsing '%s', probably not a bmap 2.0 file"
% bmap_path)
print(f"Error parsing '{bmap_path}', probably not a bmap 2.0 file")
return None
return bmapDict

Expand Down Expand Up @@ -507,7 +506,7 @@ def bmap(self, path):

def copy(self):
if os.path.exists(self._path) is False:
raise IOError('{}: image not found!'.format(self._path))
raise IOError(f'{self._path}: image not found!')

image = open(self._path, 'rb')
try:
Expand Down
16 changes: 8 additions & 8 deletions mtda/console/docker.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def configure(self, conf, role='console'):
def probe(self):
self.mtda.debug(3, "console.docker.probe()")
result = self.docker.variant == "docker"
self.mtda.debug(3, "console.docker.probe(): {}".format(result))
self.mtda.debug(3, f"console.docker.probe(): {result}")
return result

def open(self):
Expand All @@ -55,7 +55,7 @@ def open(self):
self.mtda.debug(4, "console.docker.open(): already opened")

self._opened = result
self.mtda.debug(3, "console.docker.open(): {}".format(result))
self.mtda.debug(3, f"console.docker.open(): {result}")
return result

def close(self):
Expand All @@ -68,7 +68,7 @@ def close(self):
self._socket = None
self._opened = False

self.mtda.debug(3, "console.docker.close(): {}".format(result))
self.mtda.debug(3, f"console.docker.close(): {result}")
return result

""" Return number of pending bytes to read"""
Expand All @@ -81,12 +81,12 @@ def pending(self):
fcntl.ioctl(self._fd, termios.FIONREAD, avail, 1)
result = avail[0]

self.mtda.debug(3, "console.docker.pending(): {}".format(result))
self.mtda.debug(3, f"console.docker.pending(): {result}")
return result

""" Read bytes from the console"""
def read(self, n=1):
self.mtda.debug(3, "console.docker.read({})".format(n))
self.mtda.debug(3, f"console.docker.read({n})")

result = None
if self._opened is True:
Expand All @@ -101,18 +101,18 @@ def read(self, n=1):
if result is None:
result = b''

self.mtda.debug(3, "console.docker.read(): {}".format(result))
self.mtda.debug(3, f"console.docker.read(): {result}")
return result

""" Write to the console"""
def write(self, data):
self.mtda.debug(3, "console.docker.write(data={})".format(data))
self.mtda.debug(3, f"console.docker.write(data={data})")

result = None
if self._opened is True:
result = os.write(self._fd, data)

self.mtda.debug(3, "console.docker.write(): {}".format(result))
self.mtda.debug(3, f"console.docker.write(): {result}")
return result


Expand Down
Loading

0 comments on commit 3195f4e

Please sign in to comment.