From a0734c9b48dae7be1d0468b8a83b78e1e2585387 Mon Sep 17 00:00:00 2001 From: "Brian S. Stephan" Date: Fri, 12 Apr 2024 18:55:54 -0500 Subject: [PATCH] add method to search for version strings in binaries Signed-off-by: Brian S. Stephan --- gp2040ce_bintools/builder.py | 15 +++++++++++++++ tests/test_builder.py | 10 ++++++++++ 2 files changed, 25 insertions(+) diff --git a/gp2040ce_bintools/builder.py b/gp2040ce_bintools/builder.py index cfc203b..3da07f8 100644 --- a/gp2040ce_bintools/builder.py +++ b/gp2040ce_bintools/builder.py @@ -6,6 +6,7 @@ SPDX-License-Identifier: GPL-3.0-or-later import argparse import copy import logging +import re from typing import Optional from google.protobuf.message import Message @@ -130,6 +131,20 @@ def concatenate_firmware_and_storage_files(firmware_filename: str, write(endpoint_out, endpoint_in, GP2040CE_START_ADDRESS, bytes(new_binary)) +def find_version_string_in_binary(binary: bytes) -> str: + """Search for a git describe style version string in a binary file. + + Args: + binary: the binary to search + Returns: + the first found string, or None + """ + match = re.search(b'v[0-9]+.[0-9]+.[0-9]+[A-Za-z0-9-+.]*', binary) + if match: + return match.group(0).decode(encoding='ascii') + return None + + def get_gp2040ce_from_usb() -> tuple[bytes, object, object]: """Read the firmware + config sections from a USB device. diff --git a/tests/test_builder.py b/tests/test_builder.py index 0db1f8b..369ee2d 100644 --- a/tests/test_builder.py +++ b/tests/test_builder.py @@ -134,6 +134,16 @@ def test_concatenate_to_uf2_board_only(tmp_path, firmware_binary, config_binary) assert len(content) == 2 * (2 * 1024 * 1024 - 16384) +def test_find_version_string(firmware_binary): + """Test that we can find a version string in a binary.""" + assert builder.find_version_string_in_binary(firmware_binary) == 'v0.7.5' + + +def test_dont_always_find_version_string(firmware_binary): + """Test that we can find a version string in a binary.""" + assert builder.find_version_string_in_binary(b'\x00') is None + + def test_padding_firmware(firmware_binary): """Test that firmware is padded to the expected size.""" padded = builder.pad_binary_up_to_user_config(firmware_binary)