From 99504bfde65ef32a487ed7154f50a12a523fcd75 Mon Sep 17 00:00:00 2001 From: "Brian S. Stephan" Date: Fri, 19 Apr 2024 00:12:46 -0500 Subject: [PATCH] support loading JSON files as configs to edit Signed-off-by: Brian S. Stephan --- gp2040ce_bintools/storage.py | 21 ++++++++++++--------- tests/test_storage.py | 9 +++++++++ 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/gp2040ce_bintools/storage.py b/gp2040ce_bintools/storage.py index 3a06f49..abce92f 100644 --- a/gp2040ce_bintools/storage.py +++ b/gp2040ce_bintools/storage.py @@ -241,21 +241,24 @@ def get_config_from_file(filename: str, whole_board: bool = False, allow_no_file the parsed configuration """ try: - content = get_binary_from_file(filename) + if filename[-5:] == '.json': + with open(filename) as file_: + return get_config_from_json(file_.read()) + else: + content = get_binary_from_file(filename) + if whole_board: + if board_config: + return get_config(get_board_storage_section(content)) + else: + return get_config(get_user_storage_section(content)) + else: + return get_config(content) except FileNotFoundError: if not allow_no_file: raise config_pb2 = get_config_pb2() return config_pb2.Config() - if whole_board: - if board_config: - return get_config(get_board_storage_section(content)) - else: - return get_config(get_user_storage_section(content)) - else: - return get_config(content) - def get_config_from_usb(address: int) -> tuple[Message, object, object]: """Read a config section from a USB device and provide the protobuf Message. diff --git a/tests/test_storage.py b/tests/test_storage.py index 57fc251..8b455f4 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -99,6 +99,15 @@ def test_get_board_config_from_file_whole_board_dump(): assert config.addonOptions.bootselButtonOptions.enabled is False +@with_pb2s +def test_get_board_config_from_json_file(): + """Test that we can open a JSON file and parse the config.""" + filename = os.path.join(HERE, 'test-files', 'test-config.json') + config = storage.get_config_from_file(filename, whole_board=True, board_config=True) + assert config.boardVersion == 'v0.7.6-15-g71f4512' + assert config.addonOptions.bootselButtonOptions.enabled is False + + @with_pb2s def test_get_config_from_file_file_not_fonud_ok(): """If we allow opening a file that doesn't exist (e.g. for the editor), check we get an empty config."""