From 1b02e458e2fd3954308108a3bdd05526e77b285d Mon Sep 17 00:00:00 2001 From: "Brian S. Stephan" Date: Wed, 21 Jun 2023 18:21:22 -0500 Subject: [PATCH] visualize-storage flag to print as JSON closes #3 --- gp2040ce_bintools/storage.py | 14 +++++++++++--- tests/test_commands.py | 10 ++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/gp2040ce_bintools/storage.py b/gp2040ce_bintools/storage.py index a0ae3c5..d7a18e1 100644 --- a/gp2040ce_bintools/storage.py +++ b/gp2040ce_bintools/storage.py @@ -2,6 +2,9 @@ import argparse import logging +from google.protobuf.json_format import MessageToJson +from google.protobuf.message import Message + from gp2040ce_bintools import core_parser, get_config_pb2 logger = logging.getLogger(__name__) @@ -18,7 +21,7 @@ FOOTER_MAGIC = b'\x65\xe3\xf1\xd2' ############### -def get_config(content: bytes) -> dict: +def get_config(content: bytes) -> Message: """Read the config from a GP2040-CE storage section. Args: @@ -67,7 +70,7 @@ def get_config_footer(content: bytes) -> tuple[int, int, str]: return config_size, config_crc, config_magic -def get_config_from_file(filename: str, whole_board: bool = False) -> dict: +def get_config_from_file(filename: str, whole_board: bool = False) -> Message: """Read the specified file (memory dump or whole board dump) and get back its config section. Args: @@ -114,7 +117,12 @@ def visualize(): parents=[core_parser], ) parser.add_argument('--whole-board', action='store_true', help="indicate the binary file is a whole board dump") + parser.add_argument('--json', action='store_true', help="print the config out as a JSON document") parser.add_argument('filename', help=".bin file of a GP2040-CE board's storage section, bytes 101FE000-10200000, " "or of a GP2040-CE's whole board dump if --whole-board is specified") args, _ = parser.parse_known_args() - print(get_config_from_file(args.filename, whole_board=args.whole_board)) + config = get_config_from_file(args.filename, whole_board=args.whole_board) + if args.json: + print(MessageToJson(config)) + else: + print(config) diff --git a/tests/test_commands.py b/tests/test_commands.py index 04bc72c..fa2a681 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -1,4 +1,5 @@ """Test our tools themselves to make sure they adhere to certain flags.""" +import json from subprocess import run from gp2040ce_bintools import __version__ @@ -31,3 +32,12 @@ def test_debug_storage_dump_invocation(): capture_output=True, encoding='utf8') assert 'boardVersion: "v0.7.2"' in result.stdout assert 'length of content to look for footer in: 8192' in result.stderr + + +def test_storage_dump_json_invocation(): + """Test that a normal invocation against a dump works.""" + result = run(['visualize-storage', '-P', 'tests/test-files/proto-files', '--json', + 'tests/test-files/test-storage-area.bin'], + capture_output=True, encoding='utf8') + to_dict = json.loads(result.stdout) + assert to_dict['boardVersion'] == 'v0.7.2'