Skip to content

Commit 31df2ca

Browse files
committed
use f-strings and test with 3.9
1 parent 18ba436 commit 31df2ca

3 files changed

Lines changed: 63 additions & 84 deletions

File tree

.github/workflows/python.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ jobs:
1212
runs-on: ubuntu-18.04
1313
strategy:
1414
matrix:
15-
python-version: [3.6, 3.7, 3.8]
15+
python-version: [3.6, 3.7, 3.8, 3.9]
1616
steps:
1717
- uses: actions/checkout@v2
1818
- name: Set up Python ${{ matrix.python-version }}

deploy.py

Lines changed: 53 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -177,39 +177,32 @@ def get_supported_boards():
177177

178178

179179
def fatal(msg):
180-
print("{style_begin}fatal:{style_end} {message}".format(
181-
style_begin=colorama.Fore.RED + colorama.Style.BRIGHT,
182-
style_end=colorama.Style.RESET_ALL,
183-
message=msg))
180+
print(f"{colorama.Fore.RED + colorama.Style.BRIGHT}fatal:"
181+
f"{colorama.Style.RESET_ALL} {msg}")
184182
sys.exit(1)
185183

186184

187185
def error(msg):
188-
print("{style_begin}error:{style_end} {message}".format(
189-
style_begin=colorama.Fore.RED,
190-
style_end=colorama.Style.RESET_ALL,
191-
message=msg))
186+
print(f"{colorama.Fore.RED}error:{colorama.Style.RESET_ALL} {msg}")
192187

193188

194189
def info(msg):
195-
print("{style_begin}info:{style_end} {message}".format(
196-
style_begin=colorama.Fore.GREEN + colorama.Style.BRIGHT,
197-
style_end=colorama.Style.RESET_ALL,
198-
message=msg))
190+
print(f"{colorama.Fore.GREEN + colorama.Style.BRIGHT}info:"
191+
f"{colorama.Style.RESET_ALL} {msg}")
199192

200193

201194
def assert_mandatory_binary(binary):
202195
if not shutil.which(binary):
203-
fatal(("Couldn't find {} binary. Make sure it is installed and "
204-
"that your PATH is set correctly.").format(binary))
196+
fatal((f"Couldn't find {binary} binary. Make sure it is installed and "
197+
"that your PATH is set correctly."))
205198

206199

207200
def assert_python_library(module):
208201
try:
209202
__import__(module)
210203
except ModuleNotFoundError:
211-
fatal(("Couldn't load python3 module {name}. "
212-
"Try to run: pip3 install {name}").format(name=module))
204+
fatal((f"Couldn't load python3 module {module}. "
205+
f"Try to run: pip3 install {module}"))
213206

214207

215208
class RemoveConstAction(argparse.Action):
@@ -284,7 +277,7 @@ def checked_command(self, cmd, env=None, cwd=None):
284277
subprocess.run(
285278
cmd, stdout=stdout, timeout=None, check=True, env=env, cwd=cwd)
286279
except subprocess.CalledProcessError as e:
287-
fatal("Failed to execute {}: {}".format(cmd[0], str(e)))
280+
fatal(f"Failed to execute {cmd[0]}: {str(e)}")
288281

289282
def checked_command_output(self, cmd, env=None, cwd=None):
290283
cmd_output = ""
@@ -297,7 +290,7 @@ def checked_command_output(self, cmd, env=None, cwd=None):
297290
env=env,
298291
cwd=cwd).stdout
299292
except subprocess.CalledProcessError as e:
300-
fatal("Failed to execute {}: {}".format(cmd[0], str(e)))
293+
fatal(f"Failed to execute {cmd[0]}: {str(e)}")
301294
# Unreachable because fatal() will exit
302295
return cmd_output.decode()
303296

@@ -324,7 +317,7 @@ def update_rustc_if_needed(self):
324317
current_version = self.checked_command_output(["rustc", "--version"])
325318
if not (target_toolchain[0] in current_version and
326319
target_toolchain[1] in current_version):
327-
info("Updating rust toolchain to {}".format("-".join(target_toolchain)))
320+
info(f"Updating rust toolchain to {'-'.join(target_toolchain)}")
328321
# Need to update
329322
rustup_install = ["rustup"]
330323
if self.args.verbose_build:
@@ -341,7 +334,7 @@ def update_rustc_if_needed(self):
341334
info("Rust toolchain up-to-date")
342335

343336
def build_tockos(self):
344-
info("Building Tock OS for board {}".format(self.args.board))
337+
info(f"Building Tock OS for board {self.args.board}")
345338
props = SUPPORTED_BOARDS[self.args.board]
346339
out_directory = os.path.join("third_party", "tock", "target", props.arch,
347340
"release")
@@ -353,7 +346,7 @@ def build_tockos(self):
353346
self.checked_command(["make"], cwd=props.path, env=env)
354347

355348
def build_example(self):
356-
info("Building example {}".format(self.args.application))
349+
info(f"Building example {self.args.application}")
357350
self._build_app_or_example(is_example=True)
358351

359352
def build_opensk(self):
@@ -370,12 +363,12 @@ def _build_app_or_example(self, is_example):
370363
props = SUPPORTED_BOARDS[self.args.board]
371364
rust_flags = [
372365
"-C",
373-
"link-arg=-T{}".format(props.app_ldscript),
366+
f"link-arg=-T{props.app_ldscript}",
374367
"-C",
375368
"relocation-model=static",
376369
"-D",
377370
"warnings",
378-
"--remap-path-prefix={}=".format(os.getcwd()),
371+
f"--remap-path-prefix={os.getcwd()}=",
379372
"-C",
380373
"link-arg=-icf=all",
381374
"-C",
@@ -386,8 +379,8 @@ def _build_app_or_example(self, is_example):
386379
env["APP_HEAP_SIZE"] = str(APP_HEAP_SIZE)
387380

388381
command = [
389-
"cargo", "build", "--release", "--target={}".format(props.arch),
390-
"--features={}".format(",".join(self.args.features))
382+
"cargo", "build", "--release", f"--target={props.arch}",
383+
f"--features={','.join(self.args.features)}"
391384
]
392385
if is_example:
393386
command.extend(["--example", self.args.application])
@@ -418,18 +411,16 @@ def generate_crypto_materials(self, force_regenerate):
418411
def create_tab_file(self, binaries):
419412
assert binaries
420413
assert self.args.application
421-
info("Generating Tock TAB file for application/example {}".format(
422-
self.args.application))
414+
info("Generating Tock TAB file for application/example "
415+
f"{self.args.application}")
423416
elf2tab_ver = self.checked_command_output(
424417
["elf2tab/bin/elf2tab", "--version"]).split(
425418
"\n", maxsplit=1)[0]
426419
if elf2tab_ver != "elf2tab 0.7.0":
427-
error(
428-
("Detected unsupported elf2tab version {!a}. The following "
429-
"commands may fail. Please use 0.7.0 instead.").format(elf2tab_ver))
420+
error(("Detected unsupported elf2tab version {elf2tab_ver!a}. The "
421+
"following commands may fail. Please use 0.7.0 instead."))
430422
os.makedirs(self.tab_folder, exist_ok=True)
431-
tab_filename = os.path.join(self.tab_folder,
432-
"{}.tab".format(self.args.application))
423+
tab_filename = os.path.join(self.tab_folder, f"{self.args.application}.tab")
433424
elf2tab_args = [
434425
"elf2tab/bin/elf2tab", "--deterministic", "--package-name",
435426
self.args.application, "-o", tab_filename
@@ -438,7 +429,7 @@ def create_tab_file(self, binaries):
438429
elf2tab_args.append("--verbose")
439430
stack_sizes = set()
440431
for arch, app_file in binaries.items():
441-
dest_file = os.path.join(self.tab_folder, "{}.elf".format(arch))
432+
dest_file = os.path.join(self.tab_folder, f"{arch}.elf")
442433
shutil.copyfile(app_file, dest_file)
443434
elf2tab_args.append(dest_file)
444435
# extract required stack size directly from binary
@@ -452,9 +443,8 @@ def create_tab_file(self, binaries):
452443
error("Detected different stack sizes across tab files.")
453444

454445
elf2tab_args.extend([
455-
"--stack={}".format(stack_sizes.pop()),
456-
"--app-heap={}".format(APP_HEAP_SIZE), "--kernel-heap=1024",
457-
"--protected-region-size=64"
446+
f"--stack={stack_sizes.pop()}", f"--app-heap={APP_HEAP_SIZE}",
447+
"--kernel-heap=1024", "--protected-region-size=64"
458448
])
459449
if self.args.elf2tab_output:
460450
output = self.checked_command_output(elf2tab_args)
@@ -464,7 +454,7 @@ def create_tab_file(self, binaries):
464454

465455
def install_tab_file(self, tab_filename):
466456
assert self.args.application
467-
info("Installing Tock application {}".format(self.args.application))
457+
info(f"Installing Tock application {self.args.application}")
468458
board_props = SUPPORTED_BOARDS[self.args.board]
469459
args = copy.copy(self.tockloader_default_args)
470460
setattr(args, "app_address", board_props.app_address)
@@ -477,8 +467,8 @@ def install_tab_file(self, tab_filename):
477467
try:
478468
tock.install(tabs, replace="yes", erase=args.erase)
479469
except TockLoaderException as e:
480-
fatal("Couldn't install Tock application {}: {}".format(
481-
self.args.application, str(e)))
470+
fatal("Couldn't install Tock application "
471+
f"{self.args.application}: {str(e)}")
482472

483473
def get_padding(self):
484474
padding = tbfh.TBFHeaderPadding(
@@ -490,8 +480,8 @@ def install_tock_os(self):
490480
board_props = SUPPORTED_BOARDS[self.args.board]
491481
kernel_file = os.path.join("third_party", "tock", "target",
492482
board_props.arch, "release",
493-
"{}.bin".format(self.args.board))
494-
info("Flashing file {}.".format(kernel_file))
483+
f"{self.args.board}.bin")
484+
info(f"Flashing file {kernel_file}.")
495485
with open(kernel_file, "rb") as f:
496486
kernel = f.read()
497487
args = copy.copy(self.tockloader_default_args)
@@ -501,7 +491,7 @@ def install_tock_os(self):
501491
try:
502492
tock.flash_binary(kernel, board_props.kernel_address)
503493
except TockLoaderException as e:
504-
fatal("Couldn't install Tock OS: {}".format(str(e)))
494+
fatal(f"Couldn't install Tock OS: {str(e)}")
505495

506496
def install_padding(self):
507497
padding = self.get_padding()
@@ -514,7 +504,7 @@ def install_padding(self):
514504
try:
515505
tock.flash_binary(padding, args.address)
516506
except TockLoaderException as e:
517-
fatal("Couldn't install padding: {}".format(str(e)))
507+
fatal(f"Couldn't install padding: {str(e)}")
518508

519509
def clear_apps(self):
520510
args = copy.copy(self.tockloader_default_args)
@@ -530,8 +520,7 @@ def clear_apps(self):
530520
tock.erase_apps()
531521
except TockLoaderException as e:
532522
# Erasing apps is not critical
533-
info(("A non-critical error occurred while erasing "
534-
"apps: {}".format(str(e))))
523+
info(f"A non-critical error occurred while erasing apps: {str(e)}")
535524

536525
def clear_storage(self):
537526
if self.args.programmer == "none":
@@ -546,16 +535,15 @@ def clear_storage(self):
546535
try:
547536
tock.flash_binary(storage, board_props.storage_address)
548537
except TockLoaderException as e:
549-
fatal("Couldn't erase the persistent storage: {}".format(str(e)))
538+
fatal(f"Couldn't erase the persistent storage: {str(e)}")
550539
return 0
551540
if self.args.programmer == "pyocd":
552541
self.checked_command([
553-
"pyocd", "erase", "--target={}".format(board_props.pyocd_target),
554-
"--sector", "{}+{}".format(board_props.storage_address,
555-
board_props.storage_size)
542+
"pyocd", "erase", f"--target={board_props.pyocd_target}", "--sector",
543+
f"{board_props.storage_address}+{board_props.storage_size}"
556544
])
557545
return 0
558-
fatal("Programmer {} is not supported.".format(self.args.programmer))
546+
fatal(f"Programmer {self.args.programmer} is not supported.")
559547

560548
# pylint: disable=protected-access
561549
def verify_flashed_app(self, expected_app):
@@ -582,7 +570,7 @@ def create_hex_file(self, dest_file):
582570
# Process kernel
583571
kernel_path = os.path.join("third_party", "tock", "target",
584572
board_props.arch, "release",
585-
"{}.bin".format(self.args.board))
573+
f"{self.args.board}.bin")
586574
with open(kernel_path, "rb") as kernel:
587575
kern_hex = intelhex.IntelHex()
588576
kern_hex.frombytes(kernel.read(), offset=board_props.kernel_address)
@@ -597,25 +585,25 @@ def create_hex_file(self, dest_file):
597585
final_hex.merge(padding_hex, overlap="error")
598586

599587
# Now we can add the application from the TAB file
600-
app_tab_path = "target/tab/{}.tab".format(self.args.application)
588+
app_tab_path = f"target/tab/{self.args.application}.tab"
601589
assert os.path.exists(app_tab_path)
602590
app_tab = tab.TAB(app_tab_path)
603591
if board_props.arch not in app_tab.get_supported_architectures():
604592
fatal(("It seems that the TAB file was not produced for the "
605-
"architecture {}".format(board_props.arch)))
593+
"architecture {board_props.arch}"))
606594
app_hex = intelhex.IntelHex()
607595
app_hex.frombytes(
608596
app_tab.extract_app(board_props.arch).get_binary(
609597
board_props.app_address),
610598
offset=board_props.app_address)
611599
final_hex.merge(app_hex)
612-
info("Generating all-merged HEX file: {}".format(dest_file))
600+
info(f"Generating all-merged HEX file: {dest_file}")
613601
final_hex.tofile(dest_file, format="hex")
614602

615603
def check_prerequisites(self):
616604
if not tockloader.__version__.startswith("1.5."):
617-
fatal(("Your version of tockloader seems incompatible: found {}, "
618-
"expected 1.5.x.".format(tockloader.__version__)))
605+
fatal(("Your version of tockloader seems incompatible: found "
606+
f"{tockloader.__version__}, expected 1.5.x."))
619607

620608
if self.args.programmer == "jlink":
621609
assert_mandatory_binary("JLinkExe")
@@ -636,7 +624,7 @@ def check_prerequisites(self):
636624
nrfutil_version = __import__("nordicsemi.version").version.NRFUTIL_VERSION
637625
if not nrfutil_version.startswith("6."):
638626
fatal(("You need to install nrfutil python3 package v6.0 or above. "
639-
"Found: {}".format(nrfutil_version)))
627+
"Found: {nrfutil_version}"))
640628
if not SUPPORTED_BOARDS[self.args.board].nordic_dfu:
641629
fatal("This board doesn't support flashing over DFU.")
642630

@@ -680,7 +668,7 @@ def run(self):
680668
# Install padding and application if needed
681669
if self.args.application:
682670
self.install_padding()
683-
self.install_tab_file("target/tab/{}.tab".format(self.args.application))
671+
self.install_tab_file(f"target/tab/{self.args.application}.tab")
684672
if self.verify_flashed_app(self.args.application):
685673
info("You're all set!")
686674
return 0
@@ -692,22 +680,22 @@ def run(self):
692680
return 0
693681

694682
if self.args.programmer in ("pyocd", "nordicdfu", "none"):
695-
dest_file = "target/{}_merged.hex".format(self.args.board)
683+
dest_file = f"target/{self.args.board}_merged.hex"
696684
os.makedirs("target", exist_ok=True)
697685
self.create_hex_file(dest_file)
698686

699687
if self.args.programmer == "pyocd":
700688
info("Flashing HEX file")
701689
self.checked_command([
702-
"pyocd", "flash", "--target={}".format(board_props.pyocd_target),
690+
"pyocd", "flash", f"--target={board_props.pyocd_target}",
703691
"--format=hex", "--erase=auto", dest_file
704692
])
705693
if self.args.programmer == "nordicdfu":
706694
info("Creating DFU package")
707-
dfu_pkg_file = "target/{}_dfu.zip".format(self.args.board)
695+
dfu_pkg_file = f"target/{self.args.board}_dfu.zip"
708696
self.checked_command([
709697
"nrfutil", "pkg", "generate", "--hw-version=52", "--sd-req=0",
710-
"--application-version=1", "--application={}".format(dest_file),
698+
"--application-version=1", f"--application={dest_file}",
711699
dfu_pkg_file
712700
])
713701
info(
@@ -730,9 +718,8 @@ def run(self):
730718
info("Flashing device using DFU...")
731719
return subprocess.run(
732720
[
733-
"nrfutil", "dfu", "usb-serial",
734-
"--package={}".format(dfu_pkg_file),
735-
"--serial-number={}".format(serial_number[0])
721+
"nrfutil", "dfu", "usb-serial", f"--package={dfu_pkg_file}",
722+
f"--serial-number={serial_number[0]}"
736723
],
737724
check=False,
738725
timeout=None,
@@ -772,7 +759,7 @@ def main(args):
772759

773760
if args.listing:
774761
# Missing check?
775-
fatal("Listing {} is not implemented.".format(args.listing))
762+
fatal(f"Listing {args.listing} is not implemented.")
776763

777764
OpenSKInstaller(args).run()
778765

0 commit comments

Comments
 (0)